HandleManager.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Runtime.InteropServices;
  6. using UnityEngine;
  7. public class HandleManager
  8. {
  9. public delegate bool WNDENUMPROC(IntPtr hwnd, uint lParam);
  10. [DllImport("user32.dll", SetLastError = true)]
  11. public static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, uint lParam);
  12. [DllImport("user32.dll", SetLastError = true)]
  13. public static extern IntPtr GetParent(IntPtr hWnd);
  14. [DllImport("user32.dll")]
  15. public static extern uint GetWindowThreadProcessId(IntPtr hWnd, ref uint lpdwProcessId);
  16. [DllImport("kernel32.dll")]
  17. public static extern void SetLastError(uint dwErrCode);
  18. public static IntPtr GetProcessWnd()
  19. {
  20. IntPtr ptrWnd = IntPtr.Zero;
  21. // 当前进程 ID
  22. uint pid = (uint)Process.GetCurrentProcess().Id;
  23. bool bResult = EnumWindows(new WNDENUMPROC(delegate (IntPtr hwnd, uint lParam)
  24. {
  25. uint id = 0;
  26. if (GetParent(hwnd) == IntPtr.Zero)
  27. {
  28. GetWindowThreadProcessId(hwnd, ref id);
  29. // 找到进程对应的主窗口句柄
  30. if (id == lParam)
  31. {
  32. // 把句柄缓存起来
  33. ptrWnd = hwnd;
  34. // 设置无错误
  35. SetLastError(0);
  36. // 返回 false 以终止枚举窗口
  37. return false;
  38. }
  39. }
  40. return true;
  41. }), pid);
  42. return (!bResult && Marshal.GetLastWin32Error() == 0) ? ptrWnd : IntPtr.Zero;
  43. }
  44. }