Skip to content

Commit d92e853

Browse files
authored
Create WindowAlwaysOnTop.cs
1 parent 0cd5d2f commit d92e853

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// keep executable window always on top, good for multiplayer testing
2+
3+
using System;
4+
using System.Runtime.InteropServices;
5+
using UnityEngine;
6+
7+
namespace UnityLibrary
8+
{
9+
public class WindowAlwaysOnTop : MonoBehaviour
10+
{
11+
// https://stackoverflow.com/a/34703664/5452781
12+
private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
13+
private const UInt32 SWP_NOSIZE = 0x0001;
14+
private const UInt32 SWP_NOMOVE = 0x0002;
15+
private const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;
16+
17+
[DllImport("user32.dll")]
18+
[return: MarshalAs(UnmanagedType.Bool)]
19+
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
20+
21+
// https://forum.unity.com/threads/unity-window-handle.115364/#post-1650240
22+
[DllImport("user32.dll")]
23+
private static extern IntPtr GetActiveWindow();
24+
25+
public static IntPtr GetWindowHandle()
26+
{
27+
return GetActiveWindow();
28+
}
29+
30+
void Awake()
31+
{
32+
// TODO save current window pos to player prefs on exit, then can open into same position next time
33+
#if !UNITY_EDITOR
34+
Debug.Log("Make window stay on top");
35+
SetWindowPos(GetActiveWindow(), HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
36+
#endif
37+
}
38+
}
39+
}

0 commit comments

Comments
 (0)