静态方法,直接上代码吧:
1 using System; 2 using System.Runtime.InteropServices; 3 4 namespace Macroresolute 5 { 6 public static class ProcessEx 7 { 8 private static class NativeMethods 9 { 10 internal const uint GW_OWNER = 4; 11 12 internal delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam); 13 14 [DllImport("User32.dll", CharSet = CharSet.Auto)] 15 internal static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam); 16 17 [DllImport("User32.dll", CharSet = CharSet.Auto)] 18 internal static extern int GetWindowThreadProcessId(IntPtr hWnd, out IntPtr lpdwProcessId); 19 20 [DllImport("User32.dll", CharSet = CharSet.Auto)] 21 internal static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd); 22 23 [DllImport("User32.dll", CharSet = CharSet.Auto)] 24 internal static extern bool IsWindowVisible(IntPtr hWnd); 25 } 26 27 public static IntPtr GetMainWindowHandle(int processId) 28 { 29 IntPtr MainWindowHandle = IntPtr.Zero; 30 31 NativeMethods.EnumWindows(new NativeMethods.EnumWindowsProc((hWnd, lParam) => 32 { 33 IntPtr PID; 34 NativeMethods.GetWindowThreadProcessId(hWnd, out PID); 35 36 if (PID == lParam && 37 NativeMethods.IsWindowVisible(hWnd) && 38 NativeMethods.GetWindow(hWnd, NativeMethods.GW_OWNER) == IntPtr.Zero) 39 { 40 MainWindowHandle = hWnd; 41 return false; 42 } 43 44 return true; 45 46 }), new IntPtr(processId)); 47 48 return MainWindowHandle; 49 } 50 } 51 }
52