globalmousekeyhook icon indicating copy to clipboard operation
globalmousekeyhook copied to clipboard

Application Doesn't shut down when using Mouse Hooks

Open RickStrahl opened this issue 9 years ago • 2 comments

I have a WPF application where I hook mouse events - specifically I enable a mouse hook to detect any clicks and if one is detected unhook the handler and dispose immediately.

When shutting down the application hangs after my code is done processing - in debug the debugger keeps running and I have to manually kill the app.

Here's my (truncated code).

Hookup (on Mouseclick on form):

private IKeyboardMouseEvents GlobalMouseHandler;

void StartCapture()
{
           ...
 
        GlobalMouseHandler = Hook.GlobalEvents();
        GlobalMouseHandler.MouseDownExt += GlobalMouseHandlerMouseDownExt;
}

Result handler:

private void GlobalMouseHandlerMouseDownExt(object sender, MouseEventExtArgs e)
{
            Debug.WriteLine("Mouse Click handled");
            this.Invoke(new Action(StopCapture));            
}
internal void StopCapture() {
        GlobalMouseHandler.MouseDownExt -= GlobalMouseHandlerMouseDownExt;
         GlobalMouseHandler.Dispose();
          GlobalMouseHandler = null;

            ...
}

The mouse events are firing properly - the problem is the release at the end of the application. I'm trying to activate the hook just for the short period that I need it for - ie. detect a click to accept my capture - then unhook immediately.

If I remove the above code the application terminates properly. With it in - the application won't shut down and hang on shutdown.

RickStrahl avatar Nov 03 '16 12:11 RickStrahl

Here's some more info on this particular issue: It appears the problem occurs if the window stack is different when the global handler is detached than when it was attached the hook won't disconnect properly and leak a handle.

In my specifc scenario I create new windows and overlay them on the screen, capture the mouseclick and disconnect the hook. Because a new window was opened in between and not released the application will hang on shutdown.

If I instead first release the window that was opened after the hook was attached, before the hook is unloaded the application releases fine.

RickStrahl avatar Nov 13 '16 11:11 RickStrahl

GlobalMouseHandler.Dispose() is your friend :) Still mouse lags on termination which is nasty.

panthernet avatar Jun 06 '17 08:06 panthernet