C# 获取应用程序的窗口句柄
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/820909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Application's Window Handles
提问by user361526
I'm building an app that given another app mainWindowhandle it collects information about the window state. I have no problem collecting information about child windows, but I can not access the other open windows of an application or even the menus. Is there any way of getting all window handles of an application?
我正在构建一个应用程序,该应用程序为另一个应用程序 mainWindowhandle 收集有关窗口状态的信息。我收集有关子窗口的信息没有问题,但我无法访问应用程序的其他打开窗口,甚至无法访问菜单。有没有办法获取应用程序的所有窗口句柄?
采纳答案by Tim Robinson
You could do what Process.MainWindowHandle
appears to do: use P/Invoke to call the EnumWindows
function, which invokes a callback method for every top-level window in the system.
您可以做Process.MainWindowHandle
看起来像做的事情:使用 P/Invoke 调用该EnumWindows
函数,该函数为系统中的每个顶级窗口调用一个回调方法。
In your callback, call GetWindowThreadProcessId
, and compare the window's process id with Process.Id
; if the process ids match, add the window handle to a list.
在您的回调中,调用GetWindowThreadProcessId
并将窗口的进程 ID 与Process.Id
;进行比较。如果进程 ID 匹配,则将窗口句柄添加到列表中。
回答by Mez
First, you'll have to get the windowhandle of the application's mainwindow.
首先,您必须获得应用程序主窗口的窗口句柄。
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
IntPtr hWnd = (IntPtr)FindWindow(windowName, null);
Then, you can use this handle to get all childwindows:
然后,您可以使用此句柄获取所有子窗口:
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam);
private List<IntPtr> GetChildWindows(IntPtr parent)
{
List<IntPtr> result = new List<IntPtr>();
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;
}