我正在构建一个应用程序给另一个应用程序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<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;  
}   
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top