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