views:

28

answers:

1

I'm trying to setup mouse hook on background thread.

delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam);
LowLevelMouseProc _proc = HookCallback;
SetWindowsHookEx(PInvoke.WH_MOUSE_LL, _proc, IntPtr.Zero, 0);

and

IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam){/**/}

If I put this on the main window thread everything works until window has to do more complicated work which causes mouse to stop responding for the duration of that work (updating multiple children in panel for example).

If I start a new Thread and from there set up the hook, the problem is the thread simply exits after setting up the hook and callback function is never called.

Is there a way to keep thread alive for this purpose? Or if another way exists for hooking up mouse without risking unresponsive behavior?

I accidentaly noticed that when worker thread executes

GetMessage(out msg, new IntPtr(0), 0, 0);

No message is ever recieved but thread is being kept alive for the required purpose. Also I need an elegant way to close the thread, but GetMessage never returns.

I don't quite understand all these messages, I simply want to be able to hook up mouse and secure it against freezing.

Any help is appriciated.

A: 

In your hook callback method simply launch a new thread. Something like this:

IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
    ThreadPool.QueueUserWorkItem(obj =>
    {
        // do whatever ...
    });
}

Don't forget to invoke on your main thread if your processing requires access to your forms on controls.

EDIT:

If you're doing something on your main form thread that is freezing up the UI, you should consider doing that action in a background thread instead of the main thread. When you need to update the controls as a result of your processing, then you can invoke.

this.WhateverControl.Invoke( /* ... /* );

Matthew Ferreira