C#PInvoke从已知窗口查找子窗口的窗口句柄

C#PInvoke从已知窗口查找子窗口的窗口句柄,c#,pinvoke,C#,Pinvoke,我目前正试图通过C#pinvoke使用SendMessage从子窗口获取一些文本。但是,我以前尝试将窗口句柄硬核化失败,因为值在应用程序启动时发生更改。是否有可靠的方法获取此子窗口的窗口句柄?Winspector spy显示此窗口的类名为RichEdit20W。我目前的代码如下: IntPtr hWnd= (IntPtr) 0xA0E88; // Hardcode window handle int txtlen = SendMessage(hWnd, WM_GETTEXTL

我目前正试图通过C#pinvoke使用SendMessage从子窗口获取一些文本。但是,我以前尝试将窗口句柄硬核化失败,因为值在应用程序启动时发生更改。是否有可靠的方法获取此子窗口的窗口句柄?Winspector spy显示此窗口的类名为RichEdit20W。我目前的代码如下:

IntPtr hWnd= (IntPtr) 0xA0E88; // Hardcode window handle


        int txtlen = SendMessage(hWnd, WM_GETTEXTLENGTH, 20, null);
        StringBuilder text = new StringBuilder(txtlen);
        int RetVal = SendMessage(hWnd, WM_GETTEXT, text.Capacity, text);

如果可以获得顶级窗口(带有标题栏的窗口),则可以使用递归遍历子窗口。这允许您指定窗口的文本(因为您不知道,所以使用null)和/或类(您知道)


您可以使用以下命令PInvoke API
[FindWindow][1]
以获得顶级窗口,或者更好,如果您知道流程名称:

Process[] processes = Process.GetProcessesByName("yourprocessname");

foreach (Process p in processes)

{

    IntPtr pFoundWindow = p.MainWindowHandle;

    // Do something with the handle...

    //

}

请注意,有更多的条目,因为可能会有更多的流程实例同时运行。然后,您需要一些策略来查找顶级子级,以便精确地指向您要查找的窗口。

最后,我使用托管Windows API枚举了窗口的所有子代窗口

            var descendantwindows = childWindows[0].AllDescendantWindows; // Get all descendant windows of CMainWindow

        for (int i = 0; i<descendantwindows.Length; i++)
        {
            if (descendantwindows[i].ClassName == "RichEdit20W")
                childHandle = descendantwindows[i].HWnd;
        }
var-genderantwindows=childWindows[0]。allgenderantwindows;//获取CMainWindow的所有子代窗口
对于(int i=0;i