How can I keep an event from being delivered to the GUI until my code finished running?

Posted by Frerich Raabe on Stack Overflow See other posts from Stack Overflow or by Frerich Raabe
Published on 2010-05-26T12:41:31Z Indexed on 2010/05/26 13:11 UTC
Read the original article Hit count: 261

Filed under:
|
|
|
|

I installed a global mouse hook function like this:

mouseEventHook = ::SetWindowsHookEx( WH_MOUSE_LL, mouseEventHookFn, thisModule, 0 );

The hook function looks like this:

RESULT CALLBACK mouseEventHookFn( int code, WPARAM wParam, LPARAM lParam )
{
    if ( code == HC_ACTION ) {
        PMSLLHOOKSTRUCT mi = (PMSLLHOOKSTRUCT)lParam;
        // .. do interesting stuff ..
    }
    return ::CallNextHookEx( mouseEventHook, code, wParam, lParam );
}

Now, my problem is that I cannot control how long the 'do interesting stuff' part takes exactly. In particular, it might take longer than the LowLevelHooksTimeout defined in the Windows registry. This means that, at least on Windows XP, the system no longer delivers mouse events to my hook function. I'd like to avoid this, but at the same time I need the 'do interesting stuff' part to happen before the target GUI receives the event.

I attempted to solve this by doing the 'interesting stuff' work in a separate thread so that the mouseEventHookFn above can post a message to the worker thread and then do a return 1; immediately (which ends the hook function but avoids that the event is handed to the GUI). The idea was that the worker thread, when finished, performs the CallNextHookEx call itself.

However, this causes a crash inside of CallNextHookEx (in fact, the crash occurs inside an internal function called PhkNextValid. I assume it's not safe to call CallNextHookEx from outside a hook function, is this true?

If so, does anybody else know how I can run code (which needs to interact with the GUI thread of an application) before the GUI receives the event and avoid that my hook function blocks too long?

© Stack Overflow or respective owner

Related posts about c++

Related posts about Windows