-
-
Save mattbenic/908483ad0bedbc62ab17 to your computer and use it in GitHub Desktop.
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 | |
} |
Hey man, I gave this a go and I get a segfault.
Is there anything special you had to do to get it working?
I just copied my C:\Windows\System32\user32.dll
and C:\Windows\System32\kernel32.dll
to my Assets folder.
Mind you, it appears to work, i.e. I see the debug GUI showing a window handle, but crashes immediately after.
Hi there, no I don't recall having to do anything specific. It was approximately a million years ago :) But I don't think you should need to copy those dlls either, since most systems should have System32 on PATH? I would actually think including those dlls in your build might actually be risky, you can't be guaranteed that they would be correct for all machines the game gets installed on.
Thanks for this!
@AdamBuchweitz glad it helped someone 🙂
Changed to use GetClassName instead of GetWindowText because GetWindowText returns an empty string on some versions of Windows with certain security settings (so far GetClassName doesn't seem to have this problem). This is also better because it doesn't require the user to set a window name.