Last active
June 11, 2023 14:40
-
-
Save mattbenic/908483ad0bedbc62ab17 to your computer and use it in GitHub Desktop.
Example of using Win32 API to get specific window instance in Unity. This is useful for when running multiple instances of the same application, as the window handle can then be used to correctly position and size the different windows for multi screen use.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System; | |
using System.Runtime.InteropServices; | |
using System.Text; | |
public class SpecificInstanceOfGameExample : MonoBehaviour | |
{ | |
#region DLL Imports | |
private const string UnityWindowClassName = "UnityWndClass"; | |
[DllImport("kernel32.dll")] | |
static extern uint GetCurrentThreadId(); | |
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] | |
static extern int GetClassName(IntPtr hWnd, StringBuilder lpString, int nMaxCount); | |
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam); | |
[DllImport("user32.dll")] | |
[return: MarshalAs(UnmanagedType.Bool)] | |
static extern bool EnumThreadWindows(uint dwThreadId, EnumWindowsProc lpEnumFunc, IntPtr lParam); | |
#endregion | |
#region Private fields | |
private static IntPtr windowHandle = IntPtr.Zero; | |
#endregion | |
#region Monobehavior implementation | |
/// <summary> | |
/// Called when this component is initialized | |
/// </summary> | |
void Start() | |
{ | |
uint threadId = GetCurrentThreadId(); | |
EnumThreadWindows(threadId, (hWnd, lParam) => | |
{ | |
var classText = new StringBuilder(UnityWindowClassName.Length + 1); | |
GetClassName(hWnd, classText, classText.Capacity); | |
if (classText.ToString() == UnityWindowClassName) | |
{ | |
windowHandle = hWnd; | |
return false; | |
} | |
return true; | |
}, IntPtr.Zero); | |
Debug.Log(string.Format("Window Handle: {0}", windowHandle)); | |
} | |
void OnGUI() | |
{ | |
GUILayout.Label("Window Handle: " + windowHandle); | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this!