Processing global mouse and keyboard hooks in C #

Source: Internet
Author: User
Tags hosting

This class allows you to tap keyboard and mouse and/or to detect their activity even when an application runs in the background or does not have any user interface at all. this class raises common. net eventsKeyEventArgsAndMouseEventArgs, So you can easily retrieve any information you need.

Background

There are a number of applications that run in the background and detect user inactivity to change their mode. for example, MSN Messenger (or any other messenger ). I was going to write such an application, so I searched msdn and found "exactly" what I needed: 318804-how to: Set a Windows hook in Visual C #. net. this article describes how to tap the mouse movement, but it works only when an application is active. at the end of this article, I found this explanation:"Global hook is not supported in. NET Framework. You cannot implement global hooks in Microsoft. NET Framework ...". Anyway, I continued my research and found out that there are exceptions. There areWH_KEYBOARD_LLAndWH_MOUSE_LLHooks that can be installed globally. So, I have basically replacedWH_MOUSEWithWH_MOUSE_LLIn the msdn example, and it works.

The second step was to extract the information was ed into A. netEventArgsAnd raise the appropriate events.

I found a similar article in codeproject, under global system hooks in. net by Michael Kennedy, but what I dislike is, there is an unmanaged DLL in C ++ that is a main part of this solution. this Unmanaged DLL is in C ++, and a number of classes make it complicated to integrate it in my own tiny application.

Revisions

This article was posted in 2004 and updated in 2006. during all this time until now I receive a lot of positive feedback and recommendations. there were also a number of technology improvements like. net Framework 3.5 or Visual Studio 2008. so I have decided to update it once more.

I have refactored and improved the solution, made it more flexible, stable and efficient. But this refactoring also had some drawbacks:

  1. Number of code lines and files has grown.
  2. Backward compatibility to older. nets is lost.

That's why I attend to leave the old version also to be available for download.

Using the Code [version 2] The Simple Way

If you are developing a Windows Forms Application and prefer Drag & Drop programming, there isComponentNamedGlobalEventProviderInside the AssemblyGMA. useractivitymonitor. dll. Just drag and drop it to your form and create events using the property editor events tab.

The alternative way

Use events provided bystatic ClassHookManager. Note thatsenderObject in events is alwaysnull.

For more usage hints, see the source code of the attached demo application.

Using the Code [version 1]

To use this class in your application, you need to just create an instance of it and hang on events you wocould like to process. hooks are automatically installed when the object is created, but you can stop and start listening using appropriatepublic Methods.

Collapse copy code
UserActivityHook actHook;void MainFormLoad(object sender, System.EventArgs e){    actHook= new UserActivityHook(); // crate an instance    // hang on events    actHook.OnMouseActivity+=new MouseEventHandler(MouseMoved);    actHook.KeyDown+=new KeyEventHandler(MyKeyDown);    actHook.KeyPress+=new KeyPressEventHandler(MyKeyPress);    actHook.KeyUp+=new KeyEventHandler(MyKeyUp);}

Now, an example of how to process an event:

Collapse copy code
public void MouseMoved(object sender, MouseEventArgs e){    labelMousePosition.Text=String.Format("x={0}  y={1}", e.X, e.Y);    if (e.Clicks>0) LogWrite("MouseButton     - " + e.Button.ToString());}
Changes and updates from [version 0] to [version 1]

I 'd like to thank you all for all the useful comments in the discussion forum. there were a lot of bugs and proposals posted after this article was published on 4th June, 2004. over and over again came the same topics, and I had to refer to previous posts in the discussion, that is why I have decided to revise the Code and publish a FAQ. here is the list of the most important changes:

  • The project was converted into Visual Studio 2005
  • The problem with upper case characters is solved
  • Mouse wheel information is now supported in event arguments
  • Better Exception Handling
  • Cancellation of Keyboard Events usingHandledProperty of event arguments
  • XML documentation of functions
FAQ [version 1] Question

The project cannot be run in Visual Studio. NET 2005 in debug mode because of an exception error caused by callingSetWindowsHookEx. Why? Is it a problem of. NET 2.0?

Answer

The compiled release version works well so that cannot be. NET 2.0 problem. to workaround, you just need to uncheck the check box in the project properties that says: "enable Visual Studio hosting process ". in the menu: Project-> project properties... -> debug-> enable the Visual Studio hosting process.

Question

I need to suppress some keystrokes after I have processed them.

Answer

Just sete.HandledPropertytrueIn the key events you have processed. It prevents the keystrokes being processed by other applications.

Question:

Is it possible to convert your global hooks to application hooks which capture keystrokes and mouse movements only within the application?

Answer

Yes. Just use...

Collapse copy code
private const int WH_MOUSE = 7;private const int WH_KEYBOARD = 2;

... Everywhere, instead:

Collapse copy code
private const int WH_MOUSE_LL = 14;private const int WH_KEYBOARD_LL = 13;
Question

Does it work on Win98 (Windows ME, Windows 95 )?

Answer

Yes and no. The Global hooksWH_MOUSE_LLAndWH_KEYBOARD_LLCan be monitored only under Windows NT/2000/XP. In other cases, you can only use application hooks (WH_MOUSE and WH_KEYBOARD) Which capture keystrokes and mouse movement only within the application.

Question

I have a long delay when closing applications using hooks by clickingXButton in the titlebar. If I close the application via another event (button click) for example, that works fine.

Answer

It's a known bug of Microsoft. it has to do with the Windows themes. if you disable the Windows themes, the problem goes away. another choice is to have the hook code run in a secondary thread.

Question

How do I catch key combinations like Ctrl + Shift +?

Answer

You'll have to track which keys have gone down but not up. Only the most recently pressed key keeps sendingKeyDownMessages, but the others will still sendKeyUpWhen released. So if you make three flagsIsCtrlDown,IsShiftDown, AndIsADown, And set themtrueAtKeyDownAndfalseAtKeyUp, The expression(IsCtrlDown && IsShiftDown && IsADown)Will give you the required result.

Question

Does it works with. NET Framework 1.1 and Visual Studio 2003?

Answer

Yes. The fileUseractivityhook. CSCan be used without any changes, in a Visual Studio 2003. NET 1.1 Project.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.