获取应用程序的窗口句柄

我正在构建一个应用程序给另一个应用程序mainWindowhandle它收集有关窗口状态的信息。 我收集有关子窗口的信息没有问题,但我无法访问应用程序的其他打开窗口甚至菜单。 有没有办法获取应用程序的所有窗口句柄?

您可以执行Process.MainWindowHandle操作:使用P / Invoke调用EnumWindows函数,该函数为系统中的每个顶级窗口调用回调方法。

在你的回调中,调用GetWindowThreadProcessId ,并将窗口的进程id与Process.Id进行比较; 如果进程ID匹配,则将窗口句柄添加到列表中。

首先,您必须获取应用程序主窗口的窗口句柄。

  [DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); IntPtr hWnd = (IntPtr)FindWindow(windowName, null); 

然后,您可以使用此句柄来获取所有子窗口:

 [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam); private List GetChildWindows(IntPtr parent) { List result = new List(); GCHandle listHandle = GCHandle.Alloc(result); try { EnumWindowProc childProc = new EnumWindowProc(EnumWindow); EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle)); } finally { if (listHandle.IsAllocated) listHandle.Free(); } return result; }