Global Mouse Hooks in C#

P

paul francis

Hi

Please help because I'm really stuck:

I'm trying to write an application in C# which can be used to track
the mouse pointer position on any window. I'm trying to use a Global
mouse hook to do this but with limited success. According to the
documentation (as I understand it) you can only do Global hooks in
..Net if the delegate procedure passed to SetWindowsHookEx is external.

To get around this, I have written a function in C++ and declared it
for use in my C# program as follows:

[DllImport("MouseCallBack.dll",CharSet=CharSet.Auto,
CallingConvention=CallingConvention.StdCall)]
public static extern int MouseHookProc(int nCode, IntPtr wParam,
IntPtr lParam);

public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);

HookProc MouseHookProcedure = new HookProc(MouseHookProc);

hHook = SetWindowsHookEx(WH_MOUSE,MouseHookProcedure,
(IntPtr)0,
AppDomain.GetCurrentThreadId());

However, when I try to set the last parameter (ThreadID) of
SetWindowsHookEx to zero to make the hook Global, the hook fails. Am I
doing something wrong or can you just not do Global hooks in .Net at
all? If not, does anyone have any ideas of how to achieve my goal
without the use of global hooks?

Also, if it can be done, is it possible, using some sort of event
handler for my external "MouseHookProc" in "MouseCallBack.dll" to
callback to the C# program and notify it of the new mouse position?

Thanks in advance. Paul.
 
M

Mattias Sjögren

Paul,
Am I
doing something wrong or can you just not do Global hooks in .Net at
all?

Can't be done. If you need to use a global hook, implement it in
native code library instead.



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top