feat: setup window using the api

This commit is contained in:
Gerard Gascón 2024-04-15 01:24:13 +02:00
parent 61c18429a2
commit 19cd8e5d03
27 changed files with 1364 additions and 10 deletions

View file

@ -681,6 +681,7 @@ GameObject:
- component: {fileID: 501733678} - component: {fileID: 501733678}
- component: {fileID: 501733677} - component: {fileID: 501733677}
- component: {fileID: 501733676} - component: {fileID: 501733676}
- component: {fileID: 501733679}
m_Layer: 0 m_Layer: 0
m_Name: Main Camera m_Name: Main Camera
m_TagString: MainCamera m_TagString: MainCamera
@ -762,6 +763,21 @@ Transform:
m_Children: [] m_Children: []
m_Father: {fileID: 0} m_Father: {fileID: 0}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &501733679
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 501733675}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: a1866eebb0b62a44da3196d0f2fb1b0c, type: 3}
m_Name:
m_EditorClassIdentifier:
mouseButton: 0
modifierKey: 0
temporarilyDisableIfKeyPressed:
--- !u!1 &1050150008 --- !u!1 &1050150008
GameObject: GameObject:
m_ObjectHideFlags: 0 m_ObjectHideFlags: 0

View file

@ -1,18 +1,17 @@
#if !UNITY_EDITOR //#if !UNITY_EDITOR
using SatorImaging.AppWindowUtility; using SatorImaging.AppWindowUtility;
using UnityEngine; using UnityEngine;
namespace View { namespace View {
internal static class DisplaySetup { internal static class DisplaySetup {
[RuntimeInitializeOnLoadMethod] [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)]
private static void Setup() { private static void Setup() {
AppWindowUtility.AlwaysOnTop = true; AppWindowUtility.AlwaysOnTop = true;
AppWindowUtility.FrameVisibility = false; AppWindowUtility.FrameVisibility = false;
Vector2Int resolution = new(Screen.currentResolution.width, Screen.currentResolution.height); Vector2Int resolution = new(360, 640);
Vector2Int newPosition = new(resolution.x - Screen.width, 0); AppWindowUtility.ResizeWindowRelative(resolution.x, resolution.y);
Screen.MoveMainWindowTo(Screen.mainWindowDisplayInfo, newPosition);
} }
} }
} }
#endif //#endif

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022-2023 Sator Imaging
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 75cda0b705c535d4c92faa19625a4760
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,211 @@
App Window Utility (日本語マニュアル)
======================================
このライブラリは、Unity で作成されたアプリのウインドウスタイルをカスタマイズする為のものです。
このライブラリを使用することでアプリのウインドウを透過させたり、フレームを非表示にすること等が可能です。
![](https://github.com/sator-imaging/sator-imaging.github.io/blob/master/AppWindowUtility/images/Opacity.gif?raw=true)
# 制作・著作
Copyright © 2022-2023 Sator Imaging, all rights reserved.
# ライセンス
<p>
<details>
<summary>上記の著作権表示および本許諾表示を、ソフトウェアのすべての複製または重要な部分に記載するものとします。</summary>
```text
MIT License
Copyright (c) 2022-2023 Sator Imaging
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
</details>
</p>
# 機能
以下の機能は Unity 2020.3 LTS と HDRP 10.3.2 を Windows 10 64-bit 上で実行して動作確認しています。
#### 事前準備
以下のサンプルを動作させるには、`using SatorImaging.AppWindowUtility;` を追加して名前空間を参照しておく必要があります。
# サンプル
サンプルはコチラ。その他の機能については以下のセクションをご覧ください。
```csharp
using UnityEngine;
using SatorImaging.AppWindowUtility;
public class MyTest : MonoBehaviour
{
void Start()
{
AppWindowUtility.Transparent = true;
}
}
```
## 透過ウインドウ
`bool AppWindowUtility.Transparent { get; set; }`
アプリを透過ウインドウに設定します。ウインドウの後ろにある別のウインドウが透けて見えるようになります。
透明度は Unity のレンダリング結果に依存しているので、カメラの `Background`**Solid Color** に設定してアルファをゼロにする必要があります。
> 注: High-Definition Render Pipeline (HDRP) やその他の Scriptable Render Pipeline (SRP) ベースのレンダラーを使っている場合、Color Frame Buffer をデフォルトの RGB 10bit から RGB 16bit8bit があればそちらでも可)に設定する必要があります。
<img src="https://dl.dropbox.com/s/sntvylmfgrrfw9w/Transparent.gif?dl=1" />
## ウインドウの不透明度
`AppWindowUtility.SetWindowOpacity(byte opacity)`
ウインドウ全体の不透明度を設定します。透過ウインドウと組み合わせて使うこともできます。
<img src="https://dl.dropbox.com/s/clu72kycyq2isvn/Opacity.gif?dl=1" />
## `WindowGrabber` コンポーネント
透過ウインドウが有効になっているとタイトルバーが消えてしまうので、ウインドウを移動することが出来なくなってしまいます。
`WindowGrabber` を空の `GameObject` に追加することで、アプリのウインドウのどこかをドラッグすれば移動できるようになります。
<img src="https://dl.dropbox.com/s/oxcnjfdkdshogf0/MoveWindow_WindowGrabber.png?dl=1" />
`WindowGrabber` が有効な間も uGUI を使うことが出来ます。
<img src="https://dl.dropbox.com/s/etmsd3zb0muhltd/MoveWindow.gif?dl=1" />
## フルスクリーンモード
`bool AppWindowUtility.FullScreen { get; set; }`
ウインドウをフルスクリーンに設定します。
> 注: Unity 標準の `UnityEngine.Screen.SetResolution(width, height, isFullScreen)` ではなくコチラを使った方が App Window Utility との相性が良いです。
## 常に手前に表示Always on Top
`bool AppWindowUtility.AlwaysOnTop { get; set; }`
ウインドウがフォーカスを失っても、常に最前面に表示されるようになります。
<img src="https://dl.dropbox.com/s/sip8uw1d91osdii/AlwaysOnTop.gif?dl=1" />
## クリックスルーモード
`bool AppWindowUtility.ClickThrough { get; set; }`
アプリケーションがマウスのクリックを受け付けなくなります。
> 注: マウスを使わずにこの機能をオフにする方法を実装する必要があります。実装しなかった場合、二度とアプリに触れなくなります。
<img src="https://dl.dropbox.com/s/o27h63u7g5tg9mm/ClickThru_B.gif?dl=1" />
## ウインドウフレームの表示
`bool AppWindowUtility.FrameVisibility { get; set; }`
ウインドウのフレームを表示・非表示に設定します。
※ 透過ウインドウに設定すると、同時にフレームの表示もオフに設定されます。
## カラーキーイングウインドウ
`AppWindowUtility.SetKeyingColor(byte red, byte green, byte blue)`
アプリのウインドウ全体に対して、特定の色を透過させる機能を有効にします。
かなり特殊なので、`AppWindowUtility.Transparent` を使った方が良いです。
## 加算合成モード
Windows の場合、`AppWindowUtility.SetKeyingColor(0, 0, 0)` を設定した後に `AppWindowUtility.Transparent = true` を設定すると、透過ウインドウが加算合成モードになります。
※注※ これは Windows のバグの可能性があります。
<img src="https://dl.dropbox.com/s/nt5mmncsz6cfvh6/AdditiveComposition.gif?dl=1" />
# 注意点
## プレイヤー設定Player Settings
正しく動作させるためには、`Use DXGI Flip Model Swapchain for D3D11` をオフに設定する必要があります。
※ App Window Utility が期待通りに動作しない場合、以下のプレイヤー設定を参考にしてください。
<img src="https://dl.dropbox.com/s/72ii6o5dj7yxqtt/Notes_PlayerSettings.png?dl=1" />
## High-Definition Render Pipeline (HDRP) と同時に使用する場合
`Color Buffer Format` は必ず RGB 16bitまたはホスト OS が対応しているフォーマット)に設定する必要があります。
Scriptable Render Pipeline (SRP) ベースのレンダラーは同様の設定が必要になります。
<img src="https://dl.dropbox.com/s/d1qieutmog4npbw/Notes_HDRP.png?dl=1" />
## 透過ウインドウとウィンドウフレームの表示
`Transparent = true` を設定した後に `FrameVisibility = true` を設定すると、アプリの背景が非表示になった状態でウインドウフレームが表示されます。結果としてウインドウ全体がフレームの色で塗りつぶされることになります。
<img src="https://dl.dropbox.com/s/sr55jdguin250ic/Notes_TransparentThenShowFrame.gif?dl=1" />

View file

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: d758220231f2af24194359c04ba3c6c3
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,218 @@
App Window Utility
==================
This utility is for Unity to configure application window style.
With this utility, you can make your application window transparent, frameless and more.
![](https://github.com/sator-imaging/sator-imaging.github.io/blob/master/AppWindowUtility/images/Opacity.gif?raw=true)
Copyright
=========
Copyright &copy; 2022-2023 Sator Imaging, all rights reserved.
License
=======
<p>
<details>
<summary>The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.</summary>
```text
MIT License
Copyright (c) 2022-2023 Sator Imaging
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
</details>
</p>
Features
========
Features are tested with Unity 2020.3 LTS and HDRP 10.3.2 on Windows 10 64-bit.
#### Prerequisites
`using SatorImaging.AppWindowUtility;` is required to make the following examples work.
Sample
======
Here is a sample code. See the following sections for more options.
```csharp
using UnityEngine;
using SatorImaging.AppWindowUtility;
public class MyTest : MonoBehaviour
{
void Start()
{
AppWindowUtility.Transparent = true;
}
}
```
## Transparent Window
`bool AppWindowUtility.Transparent { get; set; }`
This will make application window transparent. In other words, you can see behind through application window.
Transparency is based on Unity's rendering result. So that you need to set camera background to **Solid Color** with alpha is set to zero.
> NOTE: If you use High-Definition Render Pipeline (HDRP) or something based on Scriptable Render Pipeline (SRP), Color Frame Buffer setting needs to be set to RGB 16bit (or 8bit if available). Unity's default is RGB 10bit that Operating System doesn't support.
![](https://github.com/sator-imaging/sator-imaging.github.io/blob/master/AppWindowUtility/images/Transparent.gif?raw=true)
## Window Opacity
`AppWindowUtility.SetWindowOpacity(byte opacity)`
This will set overall window opacity. It works with see-thru window.
![](https://github.com/sator-imaging/sator-imaging.github.io/blob/master/AppWindowUtility/images/Opacity.gif?raw=true)
## `WindowGrabber` Component
With Transparent enabled, window has no title bar so that you need a way to move window.
`WindowGrabber` adds an ability to move window by dragging any area of application window.
To add this feature, create empty GameObject and attach `WindowGrabber` component.
![](https://github.com/sator-imaging/sator-imaging.github.io/blob/master/AppWindowUtility/images/MoveWindow_WindowGrabber.png?raw=true)
> You can still use uGUI controls if WindowGrabber is used.
![](https://github.com/sator-imaging/sator-imaging.github.io/blob/master/AppWindowUtility/images/MoveWindow.gif?raw=true)
## Full Screen Mode
`bool AppWindowUtility.FullScreen { get; set; }`
This will make window full screen or not.
> NOTE: Use this instead of Unity's built-in `UnityEngine.Screen.SetResolution(width, height, isFullScreen)` and `UnityEngine.Screen.fullScreen` to work better with App Window Utility.
## Always on Top
`bool AppWindowUtility.AlwaysOnTop { get; set; }`
This will make application window stay on top of other windows while another application has focus.
![](https://github.com/sator-imaging/sator-imaging.github.io/blob/master/AppWindowUtility/images/AlwaysOnTop.gif?raw=true)
## Click-Thru Mode
`bool AppWindowUtility.ClickThrough { get; set; }`
This make application window non-clickable.
> NOTE: You must implement a way to disable this feature not using mouse click. If not implemented, you cannot touch your application anymore.
![](https://github.com/sator-imaging/sator-imaging.github.io/blob/master/AppWindowUtility/images/ClickThru_B.gif?raw=true)
## Window Frame Visibility
`bool AppWindowUtility.FrameVisibility { get; set; }`
This will set window frame visibile or invisible.
> NOTE: When enable transparent window, window frame will be automatically hidden.
## Color-Keying Window
`AppWindowUtility.SetKeyingColor(byte red, byte green, byte blue)`
This will **Keying** specified color from application window.
It's strongly recommended to use `AppWindowUtility.Transparent` instead of this.
## Additive Composition Mode
On Windows, applying `AppWindowUtility.SetKeyingColor(0, 0, 0)` and then `AppWindowUtility.Transparent = true` will change window composition mode to "Additive".
> NOTE: This behaviour could be a bug of Windows.
![](https://github.com/sator-imaging/sator-imaging.github.io/blob/master/AppWindowUtility/images/AdditiveComposition.gif?raw=true)
Important Notes
===============
## Player Settings
**Use DXGI Flip Model Swapchain for D3D11** must be turned off to work correctly.
> If App Window Utility doesn't work as you expected, see Player Settings below for reference.
![](https://github.com/sator-imaging/sator-imaging.github.io/blob/master/AppWindowUtility/images/Notes_PlayerSettings.png?raw=true)
## Using with High-Definition Render Pipeline (HDRP)
**Color Buffer Format** must be RGB 16bit (or something supported on Host OS) to work correctly.
Other renderer based on Scriptable Render Pipeline (SRP) needs setting like this too.
![](https://github.com/sator-imaging/sator-imaging.github.io/blob/master/AppWindowUtility/images/Notes_HDRP.png?raw=true)
## Transparent and Frame Visibility
If you apply `Transparent = true` and then `FrameVisibility = true`, it will remove background filling from application window. Result is below, as you can see, background is filled with window frame color.
![](https://github.com/sator-imaging/sator-imaging.github.io/blob/master/AppWindowUtility/images/Notes_TransparentThenShowFrame.gif?raw=true)

View file

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: cdd8ee2bf33993e488e1c424e31bb637
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ad51b1d2ac33ed143b5f846b075be634
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,114 @@
using UnityEngine;
namespace SatorImaging.AppWindowUtility
{
public static class AppWindowUtility
{
public static IPlatformDependent platform;
public static bool AlwaysOnTopSupported { get => platform?.AlwaysOnTopSupported ?? false; }
public static bool AlwaysOnTop
{
get => platform?.GetAlwaysOnTop() ?? false;
set => platform?.SetAlwaysOnTop(value);
}
public static bool TransparentSupported { get => platform?.TransparentSupported ?? false; }
public static bool Transparent
{
get => platform?.GetTransparent() ?? false;
set => platform?.SetTransparent(value);
}
public static bool FrameVisiblitySupported { get => platform?.FrameVisibilitySupported ?? false; }
public static bool FrameVisibility
{
get => platform?.GetFrameVisibility() ?? true;
set => platform?.SetFrameVisibility(value);
}
public static bool ClickThroughSupported { get => platform?.ClickThroughSupported ?? false; }
public static bool ClickThrough
{
get => platform?.GetClickThrough() ?? false;
set => platform?.SetClickThrough(value);
}
public static bool AsWallpaperSupported { get => platform?.AsWallpaperSupported ?? false; }
public static bool AsWallpaper
{
get => platform?.GetAsWallpaper() ?? false;
set => platform?.SetAsWallpaper(value);
}
public static bool KeyingColorSupported { get => platform?.KeyingColorSupported ?? false; }
public static void SetKeyingColor(byte red, byte green, byte blue)
=> platform?.SetKeyingColor(red, green, blue);
public static bool WindowOpacitySupported { get => platform?.WindowOpacitySupported ?? false; }
public static void SetWindowOpacity(byte opacity)
=> platform?.SetWindowOpacity(opacity);
public static bool WindowPlacementSupported { get => platform?.WindowPlacementSupported ?? false; }
public static void MoveWindowRelative(int pixelX, int pixelY)
=> platform?.MoveWindowRelative(pixelX, pixelY);
public static void MoveWindow(int pixelX, int pixelY)
=> platform?.MoveWindow(pixelX, pixelY);
public static bool WindowResizeSupported { get => platform?.WindowResizeSupported ?? false; }
public static void ResizeWindowRelative(int pixelX, int pixelY)
=> platform?.ResizeWindowRelative(pixelX, pixelY);
// fullscreen
private static int[] lastScreenSize = new int[] { 640, 480 };
private static bool isFullScreen = (Screen.width == Screen.currentResolution.width && Screen.height == Screen.currentResolution.height);
public static bool FullScreen
{
get { return isFullScreen; }
set
{
if (isFullScreen == value) return;
if (value)
{
// unity turns window frame visible when returned from fullscreen.
// so match the status BEFORE going to full screen.
FrameVisibility = true;
lastScreenSize = new int[] { Screen.width, Screen.height };
Screen.SetResolution(Screen.currentResolution.width, Screen.currentResolution.height, true);// FullScreenMode.FullScreenWindow);
}
else
{
Screen.SetResolution(lastScreenSize[0], lastScreenSize[1], false);// FullScreenMode.Windowed);
}
isFullScreen = value;
// no way to control SetResolution update timing. it's done at next frame.
// so FrameVisibility done BEFORE full screen disabled no matter when it invoked in setter.
// to make it better, simply, reset transparent state.
if (!isFullScreen) Transparent = false;
}//set
}//
}//class
}//namespace

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1f147022b54faec44aa2bf93bc5c5737
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,43 @@
namespace SatorImaging.AppWindowUtility
{
public interface IPlatformDependent
{
bool AlwaysOnTopSupported { get; }
bool GetAlwaysOnTop();
void SetAlwaysOnTop(bool enable);
bool TransparentSupported { get; }
bool GetTransparent();
void SetTransparent(bool enable);
bool FrameVisibilitySupported { get; }
bool GetFrameVisibility();
void SetFrameVisibility(bool visible);
bool ClickThroughSupported { get; }
bool GetClickThrough();
void SetClickThrough(bool enable);
bool AsWallpaperSupported { get; }
bool GetAsWallpaper();
void SetAsWallpaper(bool enable);
bool KeyingColorSupported { get; }
void SetKeyingColor(byte red, byte green, byte blue);
bool WindowOpacitySupported { get; }
void SetWindowOpacity(byte opacity);
bool WindowPlacementSupported { get; }
void MoveWindowRelative(int pixelX, int pixelY);
void MoveWindow(int x, int y);
bool WindowResizeSupported { get; }
public void ResizeWindowRelative(int relativeWidth, int relativeHeight);
}//
}//namespace

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c91b36bb61130ec4aa52b609135aa56e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,24 @@
using UnityEngine;
namespace SatorImaging.AppWindowUtility
{
static class InitializeOnLoad
{
#if UNITY_EDITOR
//[UnityEditor.InitializeOnLoadMethod]
#endif
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
static void Install()
{
#if UNITY_STANDALONE_WIN
AppWindowUtility.platform = new Windows();
#endif
}
}//class
}//namespace

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 127a7c2393583d743bd2bb10e100a3cf
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,66 @@
using UnityEngine;
using UnityEngine.EventSystems;
namespace SatorImaging.AppWindowUtility
{
public class WindowGrabber : MonoBehaviour
{
public enum MouseButton
{
Left = 0,
Right = 1,
Middle = 2,
}
public MouseButton mouseButton;
public KeyCode modifierKey = KeyCode.None;
public KeyCode[] temporarilyDisableIfKeyPressed;
private bool isDragging = false;
Vector2 targetPosition = Vector2.zero;
void Update()
{
#if UNITY_EDITOR
if(isDragging.Equals(isDragging)) return; // to avoid CS0162 warning
#endif
// do nothing if any uGUI is in use.
if (EventSystem.current?.currentSelectedGameObject) return;
// initialize dragging state. don't check modifier key.
if (Input.GetMouseButtonUp((int)mouseButton)) isDragging = false;
// key check.
foreach (var k in temporarilyDisableIfKeyPressed) if (Input.GetKey(k)) return;
if (modifierKey != KeyCode.None && !Input.GetKey(modifierKey)) return;
if (Input.GetMouseButtonDown((int)mouseButton))
{
targetPosition = Event.current.mousePosition;
isDragging = true;
}
if (isDragging && Input.GetMouseButton((int)mouseButton))
{
// do NOT use Event.current.delta. it's sampled in local window coordinate.
// and moving window while mouse dragging changes coordinate sample by sample.
// just remove the gap between current mouse position and drag starting position.
AppWindowUtility.MoveWindowRelative(
(int)(Event.current.mousePosition.x - targetPosition.x),
(int)(Event.current.mousePosition.y - targetPosition.y)
);
}
}//
}//class
}//namespace

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a1866eebb0b62a44da3196d0f2fb1b0c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: cfd42f4c85ef7c248b021f4f37c70a4c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,201 @@
#if UNITY_STANDALONE_WIN
using System;
using System.Runtime.InteropServices;
using System.Text;
using UnityEngine;
namespace SatorImaging.AppWindowUtility
{
public static class WinApi
{
[StructLayout(LayoutKind.Sequential)]
public struct DwmMargin
{
public int cxLeftWidth;
public int cxRightWidth;
public int cyTopHeight;
public int cyBottomHeight;
}
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
}
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetCursorPos(out POINT lpPoint);
public static Vector2 GetWindowsMousePosition()
{
POINT pos;
if (GetCursorPos(out pos)) return new Vector2(pos.X, pos.Y);
return Vector2.zero;
}
[DllImport("user32.dll")]
public static extern IntPtr GetActiveWindow();
[DllImport("user32.dll")]
public static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll")]
public static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
[DllImport("user32.dll")]
public static extern uint SendMessageTimeout(IntPtr hWnd, uint Msg, uint wParam, uint lParam, uint fuFlags, uint uTimeout, out uint lpdwResult);
[DllImport("user32.dll")]
public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
public static extern IntPtr FindWindowEx(IntPtr hWndParent, IntPtr hWndChild, string lpszClass, string lpszWindow);
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string className, string windowName);
public static IntPtr CurrentWindowHandle = IntPtr.Zero;
public static IntPtr GetUnityWindowHandle()
{
if (CurrentWindowHandle == IntPtr.Zero)
{
CurrentWindowHandle = FindWindow(null, Application.productName);
}
return CurrentWindowHandle;
}
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
public static bool IsWindowActive()
{
return GetUnityWindowHandle() == GetForegroundWindow();
}
[DllImport("user32.dll")]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, uint dwNewLong); /*x uint o int unchecked*/
[DllImport("user32.dll")]
public static extern uint GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool SetWindowText(IntPtr hwnd, String lpString);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, SetWindowPosFlags uFlags);
[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);
[DllImport("user32.dll")]
public static extern bool GetClientRect(IntPtr hWnd, out RECT rect);
public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
public static readonly IntPtr HWND_TOP = new IntPtr(0);
public static readonly IntPtr HWND_BOTTOM = new IntPtr(1);
[Flags()]
public enum SetWindowPosFlags : uint
{
AsynchronousWindowPosition = 0x4000,
DeferErase = 0x2000,
DrawFrame = 0x0020,
FrameChanged = 0x0020,
HideWindow = 0x0080,
DoNotActivate = 0x0010,
DoNotCopyBits = 0x0100,
IgnoreMove = 0x0002,
DoNotChangeOwnerZOrder = 0x0200,
DoNotRedraw = 0x0008,
DoNotReposition = 0x0200,
DoNotSendChangingEvent = 0x0400,
IgnoreResize = 0x0001,
IgnoreZOrder = 0x0004,
ShowWindow = 0x0040,
NoFlag = 0x0000,
}
[DllImport("Dwmapi.dll")]
public static extern uint DwmExtendFrameIntoClientArea(IntPtr hWnd, ref DwmMargin margins);
public static void SetDwmTransparent(bool enable)
{
var margins = new DwmMargin()
{
cxLeftWidth = enable ? -1 : 0,
};
DwmExtendFrameIntoClientArea(GetUnityWindowHandle(), ref margins);
}
public const int GWL_STYLE = -16;
public const uint WS_POPUP = 0x80000000;
public const uint WS_BORDER = 0x00800000;
public const uint WS_VISIBLE = 0x10000000;
public const uint WS_CAPTION = 0x00C00000;
public const uint WS_THICKFRAME = 0x00040000;
public const int GWL_EXSTYLE = -20;
public const uint WS_EX_LAYERED = 0x00080000;
public const uint WS_EX_TRANSPARENT = 0x00000020;
public const uint WS_EX_DLGMODALFRAME = 0x00000001;
public const uint WS_EX_WINDOWEDGE = 0x00000100;
public const uint WS_EX_CLIENTEDGE = 0x00000200;
public const uint WS_EX_STATICEDGE = 0x00020000;
public const int LWA_COLORKEY = 0x00000001;
public const int LWA_ALPHA = 0x00000002;
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool GetLayeredWindowAttributes(IntPtr hwnd, out uint crKey, out byte bAlpha, out uint dwFlags);
}//class
}//namespace
#endif

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d8438e9a2634454429f47962402d6be3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,298 @@
#if UNITY_STANDALONE_WIN
using System;
using UnityEngine;
namespace SatorImaging.AppWindowUtility
{
public class Windows : IPlatformDependent
{
static IntPtr hWnd;
static uint defaultWindowStyle;
static uint defaultExWindowStyle;
// unity's shader error color.
static uint defaultKeyingColor = 0xFF00FF;
static int borderWidth;
static int titleBarHeight;
private static bool isAlwaysOnTop = false;
private static bool isTransparent = false;
private static bool isFrameVisible = true;
private static bool isClickThrough = false;
private static bool isWallpaper = false;
private static bool isInitialized = false;
private static WinApi.RECT lastClientRect = new WinApi.RECT { left = 32, top = 64, right = 640, bottom = 480 };
// features supported
public bool AlwaysOnTopSupported { get; } = true;
public bool TransparentSupported { get; } = true;
public bool FrameVisibilitySupported { get; } = true;
public bool ClickThroughSupported { get; } = true;
public bool AsWallpaperSupported { get; } = true;
public bool KeyingColorSupported { get; } = true;
public bool WindowOpacitySupported { get; } = true;
public bool WindowPlacementSupported { get; } = true;
public bool WindowResizeSupported { get; } = true;
public Windows()
{
if (isInitialized) return;
hWnd = WinApi.GetUnityWindowHandle();
defaultWindowStyle = WinApi.GetWindowLong(WinApi.GetUnityWindowHandle(), WinApi.GWL_STYLE);
defaultExWindowStyle = WinApi.GetWindowLong(WinApi.GetUnityWindowHandle(), WinApi.GWL_EXSTYLE);
// initialize client rect.
WinApi.GetClientRect(hWnd, out lastClientRect);
// calculate title bar and frame size
WinApi.RECT windowRect;
WinApi.GetWindowRect(hWnd, out windowRect);
WinApi.RECT clientRect;
WinApi.GetClientRect(hWnd, out clientRect);
borderWidth = (windowRect.right - windowRect.left) - clientRect.right;
borderWidth = (int)(borderWidth * 0.5f);
titleBarHeight = (windowRect.bottom - windowRect.top) - clientRect.bottom - borderWidth;
//Debug.Log($"{typeof(AppWindowUtility).FullName}.Initialize: Title Bar {titleBarHeight}px / Border {borderWidth}px");
isInitialized = true;
}//
public void ResetStyle()
{
WinApi.SetWindowLong(hWnd, WinApi.GWL_STYLE, defaultWindowStyle);
WinApi.SetWindowLong(hWnd, WinApi.GWL_EXSTYLE, defaultExWindowStyle);
}//
public bool GetAlwaysOnTop() => isAlwaysOnTop;
public void SetAlwaysOnTop(bool enable)
{
WinApi.SetWindowPos(
hWnd,
enable ? WinApi.HWND_TOPMOST : WinApi.HWND_NOTOPMOST,
0, 0, 0, 0,
WinApi.SetWindowPosFlags.IgnoreMove | WinApi.SetWindowPosFlags.IgnoreResize
);
isAlwaysOnTop = enable;
}//
public bool GetTransparent() => isTransparent;
public void SetTransparent(bool enable)
{
if (enable)
{
SetFrameVisibility(false);
var currExStyle = WinApi.GetWindowLong(hWnd, WinApi.GWL_EXSTYLE);
WinApi.SetWindowLong(hWnd, WinApi.GWL_EXSTYLE, currExStyle & ~WinApi.WS_EX_LAYERED);
WinApi.SetDwmTransparent(true);
}
else
{
SetFrameVisibility(true);
WinApi.SetDwmTransparent(false);
}
isTransparent = enable;
}//
public void SetKeyingColor(byte red, byte green, byte blue)
{
var currExStyle = WinApi.GetWindowLong(hWnd, WinApi.GWL_EXSTYLE);
WinApi.SetWindowLong(hWnd, WinApi.GWL_EXSTYLE, currExStyle | WinApi.WS_EX_LAYERED);// | WindowsApi.WS_EX_TRANSPARENT);
var color = (uint)(blue + (green << 8) + (red << 16));
WinApi.SetLayeredWindowAttributes(hWnd, color, 0xFF, WinApi.LWA_COLORKEY);
}//
public bool GetFrameVisibility() => isFrameVisible;
public void SetFrameVisibility(bool visible)
{
if (AppWindowUtility.FullScreen) return;
if (visible == isFrameVisible) return;
if (visible)
{
// must be done BEFORE SetWindowLong
MoveWindowRelative(-borderWidth, -titleBarHeight);
//ResizeWindowRelative(borderWidth * 2, titleBarHeight + borderWidth);
WinApi.SetWindowLong(hWnd, WinApi.GWL_STYLE, defaultWindowStyle);
// to make uGUI correct.
WinApi.SetWindowPos(hWnd, IntPtr.Zero,
lastClientRect.left - borderWidth,
lastClientRect.top - titleBarHeight,
lastClientRect.right - lastClientRect.left + borderWidth * 2,
lastClientRect.bottom - lastClientRect.top + titleBarHeight + borderWidth,
WinApi.SetWindowPosFlags.FrameChanged | WinApi.SetWindowPosFlags.IgnoreMove
);
}
else
{
// store last client size for showing frame again
if (!AppWindowUtility.FullScreen)
{
WinApi.GetClientRect(hWnd, out lastClientRect);
//Debug.Log($"SetFrameVisibility: Client Rect stored.");
}
var currStyle = WinApi.GetWindowLong(hWnd, WinApi.GWL_STYLE);
WinApi.SetWindowLong(hWnd, WinApi.GWL_STYLE, currStyle & ~WinApi.WS_BORDER & ~WinApi.WS_THICKFRAME & ~WinApi.WS_CAPTION);
//// must be done AFTER SetWindowLong
MoveWindowRelative(borderWidth, titleBarHeight);
// must be change window size 2 times to work correctly, idk why.
WinApi.SetWindowPos(hWnd, IntPtr.Zero,
lastClientRect.left - borderWidth,
lastClientRect.top - titleBarHeight,
lastClientRect.right,
lastClientRect.bottom + 1,
WinApi.SetWindowPosFlags.FrameChanged | WinApi.SetWindowPosFlags.IgnoreMove
);
WinApi.SetWindowPos(hWnd, IntPtr.Zero,
lastClientRect.left - borderWidth,
lastClientRect.top - titleBarHeight,
lastClientRect.right,
lastClientRect.bottom - 1,
WinApi.SetWindowPosFlags.FrameChanged | WinApi.SetWindowPosFlags.IgnoreMove
);
}
isFrameVisible = visible;
}//
public bool GetClickThrough() => isClickThrough;
public void SetClickThrough(bool enable)
{
if (enable)
{
var currExStyle = WinApi.GetWindowLong(hWnd, WinApi.GWL_EXSTYLE);
WinApi.SetWindowLong(hWnd, WinApi.GWL_EXSTYLE, currExStyle | WinApi.WS_EX_LAYERED | WinApi.WS_EX_TRANSPARENT);
}
else
{
WinApi.SetWindowLong(hWnd, WinApi.GWL_EXSTYLE, defaultExWindowStyle);
}
isClickThrough = enable;
}//
public void SetWindowOpacity(byte opacity)
{
////////if(0xFF == opacity)
{
var currExStyle = WinApi.GetWindowLong(hWnd, WinApi.GWL_EXSTYLE);
WinApi.SetWindowLong(hWnd, WinApi.GWL_EXSTYLE, currExStyle | WinApi.WS_EX_LAYERED);
WinApi.SetLayeredWindowAttributes(hWnd, defaultKeyingColor, opacity, WinApi.LWA_ALPHA);
}
/* do not reset for combination with Transparent
else
{
ResetStyle();
}
*/
}//
public bool GetAsWallpaper() => isWallpaper;
public void SetAsWallpaper(bool enable)
{
}//
public void MoveWindowRelative(int relativeX, int relativeY)
{
if (AppWindowUtility.FullScreen) return;
WinApi.RECT rect;
WinApi.GetWindowRect(hWnd, out rect);
WinApi.SetWindowPos(hWnd, IntPtr.Zero,
rect.left + relativeX,
rect.top + relativeY,
rect.right - rect.left,
rect.bottom - rect.top,
WinApi.SetWindowPosFlags.NoFlag //ApiWindows.SetWindowPosFlags.IgnoreResize
);
}//
public void MoveWindow(int x, int y)
{
if (AppWindowUtility.FullScreen) return;
WinApi.RECT rect;
WinApi.GetWindowRect(hWnd, out rect);
WinApi.SetWindowPos(hWnd, IntPtr.Zero,
x,
y,
rect.right - rect.left,
rect.bottom - rect.top,
WinApi.SetWindowPosFlags.NoFlag //ApiWindows.SetWindowPosFlags.IgnoreResize
);
}//
public void ResizeWindowRelative(int relativeWidth, int relativeHeight)
{
if (AppWindowUtility.FullScreen) return;
WinApi.RECT rect;
WinApi.GetWindowRect(hWnd, out rect);
WinApi.SetWindowPos(hWnd, IntPtr.Zero,
rect.left,
rect.top,
relativeWidth,
relativeHeight,
WinApi.SetWindowPosFlags.NoFlag //ApiWindows.SetWindowPosFlags.IgnoreMove
);
}//
}//class
}//namespace
#endif

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 00a74ea748d2df149864a0f9d4455e24
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,14 @@
{
"name": "SatorImaging.AppWindowUtility",
"rootNamespace": "",
"references": [],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View file

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 1220ccfff01d26041a9bb8cd7ae584af
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,13 @@
{
"name": "com.sator-imaging.app-window-utility",
"displayName": "App Window Utility",
"version": "1.0.0",
"unity": "2018.3",
"description": "Utility for configuring application window style. With this utility, you can make application window transparent, frameless and more.\n\nCopyright (c) 2021 Sator Imaging, all rights reserved.",
"author": {
"name": "Sator Imaging",
"url": "https://www.sator-imaging.com/"
}
}

View file

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 9b6e7f857b825e749abd98ad9af4e67b
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,11 +1,10 @@
{ {
"dependencies": { "dependencies": {
"com.sator-imaging.app-window-utility": { "com.sator-imaging.app-window-utility": {
"version": "https://github.com/sator-imaging/AppWindowUtility.git", "version": "file:AppWindowUtility",
"depth": 0, "depth": 0,
"source": "git", "source": "embedded",
"dependencies": {}, "dependencies": {}
"hash": "92110b8c9515c3ec9056c924c113e1721b9a5bbc"
}, },
"com.unity.2d.sprite": { "com.unity.2d.sprite": {
"version": "1.0.0", "version": "1.0.0",