(转)获取指定进程的主窗口句柄
staitc类中还包含一个子的static类。
using System; using System.Runtime.InteropServices; namespace Macroresolute { public static class ProcessEx { private static class NativeMethods { internal const uint GW_OWNER = 4; internal delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam); [DllImport("User32.dll", CharSet = CharSet.Auto)] internal static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam); [DllImport("User32.dll", CharSet = CharSet.Auto)] internal static extern int GetWindowThreadProcessId(IntPtr hWnd, out IntPtr lpdwProcessId); [DllImport("User32.dll", CharSet = CharSet.Auto)] internal static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd); [DllImport("User32.dll", CharSet = CharSet.Auto)] internal static extern bool IsWindowVisible(IntPtr hWnd); } public static IntPtr GetMainWindowHandle(int processId) { IntPtr MainWindowHandle = IntPtr.Zero; NativeMethods.EnumWindows(new NativeMethods.EnumWindowsProc((hWnd, lParam) => { IntPtr PID; NativeMethods.GetWindowThreadProcessId(hWnd, out PID); if (PID == lParam && NativeMethods.IsWindowVisible(hWnd) && NativeMethods.GetWindow(hWnd, NativeMethods.GW_OWNER) == IntPtr.Zero) { MainWindowHandle = hWnd; return false; } return true; }), new IntPtr(processId)); return MainWindowHandle; } } }