Search code examples
c#pinvoke

C# PInvoke Finding the window handle of a child window from a known window


I am currently attempting to get some text from a child window using SendMessage via C# PInvoke. However, my previous attempts to hardcore the window handle failed as the value changes upon the startup of the application. Is there a way to reliably get the window handle of this child window? Winspector spy shows that the class name of this window is RichEdit20W. My current code is as follows:

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);

Solution

  • I ended up using the Managed Windows API to enumerate all descendant windows of the window.

                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;
            }