暫無描述
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BringWindowToFront.cs 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Runtime.InteropServices;
  3. namespace Unity.PlasticSCM.Editor.Tool
  4. {
  5. internal static class BringWindowToFront
  6. {
  7. internal static void ForWindowsProcess(int processId)
  8. {
  9. IntPtr handle = FindMainWindowForProcess(processId);
  10. if (IsIconic(handle))
  11. ShowWindow(handle, SW_RESTORE);
  12. SetForegroundWindow(handle);
  13. }
  14. static IntPtr FindMainWindowForProcess(int processId)
  15. {
  16. IntPtr result = IntPtr.Zero;
  17. EnumWindows(delegate (IntPtr wnd, IntPtr param)
  18. {
  19. uint windowProcessId = 0;
  20. GetWindowThreadProcessId(wnd, out windowProcessId);
  21. if (windowProcessId == processId &&
  22. IsMainWindow(wnd))
  23. {
  24. result = wnd;
  25. return false;
  26. }
  27. return true;
  28. }, IntPtr.Zero);
  29. return result;
  30. }
  31. static bool IsMainWindow(IntPtr handle)
  32. {
  33. return GetWindow(new HandleRef(null, handle), GW_OWNER) == IntPtr.Zero
  34. && IsWindowVisible(new HandleRef(null, handle));
  35. }
  36. // Delegate to filter which windows to include
  37. delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
  38. [DllImport("user32.dll")]
  39. static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);
  40. [DllImport("user32.dll", SetLastError = true)]
  41. static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
  42. [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
  43. static extern IntPtr GetWindow(HandleRef hWnd, int uCmd);
  44. [DllImport("user32.dll", CharSet = CharSet.Auto)]
  45. static extern bool IsWindowVisible(HandleRef hWnd);
  46. [DllImport("user32.dll")]
  47. static extern bool ShowWindow(IntPtr handle, int nCmdShow);
  48. [DllImport("user32.dll")]
  49. static extern bool SetForegroundWindow(IntPtr handle);
  50. [DllImport("user32.dll")]
  51. static extern bool IsIconic(IntPtr handle);
  52. const int GW_OWNER = 4;
  53. const int SW_RESTORE = 9;
  54. }
  55. }