By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,052 Members | 1,248 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,052 IT Pros & Developers. It's quick & easy.

Global Mouse Hooks in C#

P: n/a
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.
Jul 19 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
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

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/
Please reply only to the newsgroup.
Jul 19 '05 #2

P: n/a
Paul,

Here's an example of a global hook used with a VB app.

http://www.scottandmichelle.net/scot...mv?codenum=052

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/
Please reply only to the newsgroup.
Jul 19 '05 #3

P: n/a
Mattias

You are a god! Thanks, just what I was looking for.

Paul.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 19 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.