Search code examples
c++visual-studiowinapihwnd

Get Window Handle (HWND) of a window created by a library call


EDIT: I forgot to mention, I do not have source code for the DLL that creates window, so I can't actually change the function to return HWND.

I am creating a Win32 application, and am using a DLL that creates a window for me through one of its exported function "void X();" I call X() in my WinMain().

It does create a window for me. I want to get the HWND of the window that was created by this exported library function, as X() returns void, so I can use it for other API calls. Can someone tell the easiest to get the HWND?

I have searched and questions answered here, but I cant somehow figure out the exact, appropriate solution. I tried EnumWIndows() and then getting the Process ID, and then comparing with the current thread process ID. But I guess there should be a far better much more efficient and a easy way to get HWND. After all, I am in the WinMain of the process that created this window in the first place.

If I need to explain anything, that I have missed out writing here, please let me know.

I am sure that this is very basic and am missing something blatantly here. Sorry. Thanks & Regards!


Solution

  • Use a tool like Spy++ or Winspector to see all of the HWNDs created by your app, in particular their class names and window titles. Then you can copy those values into your code and make a single call to FindWindow() after the DLL has created its window, eg:

    int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
    {
        // ...
        X();
        HWND hWnd = FindWindow("ClassNameHere", "TitleHere");
        // ...
        return 0;
    }