Search code examples
c++windowswinapiwndprochwnd

Close callback or WM_CLOSE from a HWND reference


I'm calling the HtmlHelpA winapi method to display the .chm of my app. This method returns a HWND immediatelly, and the help window is shown as a separate window.

Along with the window, I set a timer for this hwnd. My problem is that I need to know when this window gets closed to kill the timer.

My first approach was trying to register the WndProc callback, but I couldn't do that because I'm not creating the window, I only have a reference to the hwnd.

Then I tried with a hook (SetWindowsHookEx) but the HOOKPROC won't bring the HWND as a parameter to the callback. Besides, I need to know the thread for this hwnd.

Is there any way to register a callback when a HWND gets closed or having a WndProc to wait for the WM_CLOSE message?


Solution

  • You want to subclass the help window. Subclassing gives you a chance to spy on all the messages going to the window proc. You do whatever additional work you need when you see a message of interest, and then pass the message on to the original window procedure for normal processing.

    LRESULT CALLBACK MyWndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp);
    
    WNDPROC fnOldProc = reinterpret_cast<WNDPROC>(::SetWindowLongPtr(hwndHelp, GWLP_WNDPROC, &MyWndProc));
    
    
    LRESULT CALLBACK MyWndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
        if (msg == WM_CLOSE) {
            // Kill your timer here.
        }
        return CallWindowProc(fnOldProc, hwnd, msg, wp, lp);
    }