Rodrigo Rivera
Rodrigo Rivera

Reputation: 177

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?

Upvotes: 3

Views: 2160

Answers (2)

Adrian McCarthy
Adrian McCarthy

Reputation: 47962

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

Upvotes: 1

Andr&#233; Caron
Andr&#233; Caron

Reputation: 45224

If required you can register a new window procedure for an existing window. Check out the documentation on SetWindowLongPtr().

Invoking it like this:

SetWindowLongPtr(hwnd, GWLP_WNDPROC, &MyCustomHelpWindowProc);

Just remember that window subclassing is very delicate. You might want to store the old window procedure somewhere and invoke that rather than DefWindowProc() for messages you are not interested in.

Upvotes: 2

Related Questions