Click here to Skip to main content
11,412,578 members (73,225 online)
Click here to Skip to main content

Global Mouse and Keyboard Library

, 8 Aug 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
Easy-to-use library with global mouse and keyboard hooks and simulators.

Introduction

This article explains how to use the mouse and keyboard library that I have created. This library consists of two things: global mouse and keyboard hooks, and global mouse and keyboard simulators.

The global hooks contain a set of events that follow the .NET event model, so they should be very simple to use if you've done anything with events before.

The simulators will actually simulate mouse movements, clicks, keyboard presses, etc. This can be useful for macro recording (which is one of the sample projects), and of course, messing with your friends. Smile | :)

Background

I've found a lot of hook and simulator code out there, but a lot of it was not very organized, and a bit hard to use. The goal here is to make a very simple and easy-to-use library for mouse and keyboard operations not natively supported by .NET.

Global Hooks

This section will explain how to use the global hooks which can capture mouse and keyboard events from any application. These events are very similar to the ones that appear on Windows controls, so they should look familiar.

Using the mouse hook:

// Create the mouse hook
MouseHook mouseHook = new MouseHook();

// Capture the events
mouseHook.MouseMove += new MouseEventHandler(mouseHook_MouseMove);
mouseHook.MouseDown += new MouseEventHandler(mouseHook_MouseDown);
mouseHook.MouseUp += new MouseEventHandler(mouseHook_MouseUp);
mouseHook.MouseWheel += new MouseEventHandler(mouseHook_MouseWheel); 

// Start watching for mouse events
mouseHook.Start();

...

// Stop watching (don't forget to do this before closing application!)
mouseHook.Stop();

Using the keyboard hook:

// Create the keyboard hook
KeyboardHook keyboardHook = new KeyboardHook();

// Capture the events
keyboardHook.KeyDown += new KeyEventHandler(keyboardHook_KeyDown);
keyboardHook.KeyUp += new KeyEventHandler(keyboardHook_KeyUp);
keyboardHook.KeyPress += new KeyPressEventHandler(keyboardHook_KeyPress);

// Start watching for keyboard events
keyboardHook.Start();

...

// Stop watching (don't forget to do this before closing application!)
keyboardHook.Stop();

Note: When you are setting the events, Visual Studio will name and create a blank method for you. You only need to type this much on the event ...

keyboardHook.KeyDown +=

...and then hit TAB two times. Visual Studio will finish the rest of the line, and will go out and create the blank method for you. This is a nice feature, and saves a lot of time; use it!

Simulators

This section will explain how to use the the mouse and keyboard simulators to simulate mouse clicks and keyboard key presses. Both the KeyboardSimulator and MouseSimulator classes are static, so they are pretty simple to use.

Simulating mouse events:

// Press Left Mouse Button Down
MouseSimulator.MouseDown(MouseButton.Left);

// Let Left Mouse Button Up
MouseSimulator.MouseUp(MouseButton.Left);

// Press down and Let up Left Mouse Button
// (equivalent to two lines above)
MouseSimulator.Click(MouseButton.Left);

// Double click Left Mouse button
// (equivalent to two Click()s above)
MouseSimulator.DoubleClick(MouseButton.Left);

The code above is used to simulate pressing and letting up a certain mouse button. The one parameter is just an enumeration of the three possible mouse buttons: Left, Right, and Middle.

Moving the mouse position:

// Move mouse cursor to Top Left of screen
MouseSimulator.X = 0;
MouseSimulator.Y = 0;

// Move the mouse cursor to the right by 20 pixels
MouseSimulator.X += 20;

The X and Y above are properties. You can use them to get the current position of the mouse cursor, or you can set them to move the mouse cursor to a new location.

Keyboard simulators:

// Press the A Key Down
KeyboardSimulator.KeyDown(Keys.A);

// Let the A Key back up
KeyboardSimulator.KeyUp(Keys.A);

// Press A down, and let up (same as two above)
KeyboardSimulator.KeyPress(Keys.A);

The code above will simulate keyboard key presses. You can press a key down (first line), which doesn't let it up yet. The second line, KeyUp, will release a key that has been pressed down, the third line with do both steps in one shot.

I also included some standard keyboard shortcuts. These can all be done with the code above, but it simplifies it a bit, and makes the code a bit more readable and obvious.

// Simulate (Ctrl + C) shortcut, which is copy for most applications
KeyboardSimulator.SimulateStandardShortcut(StandardShortcut.Copy);

// This does the same as above
KeyboardSimulator.KeyDown(Keys.Control);
KeyboardSimulator.KeyPress(Keys.C);
KeyboardSimulator.KeyUp(Keys.Control);

The code above does the exact same thing twice, except the first is a bit shorter and more obvious.

A Sample Application: Global Macro Recorder

A macro recorder is a great example for this library, since we can use the hooks to record the macro, and the simulators to play back.

Check out the Macro project in the downloadable source code.

Future Additions / Revisions

I'm going to edit and add to this library over time as I get feedback. If you think something should be added, changed, or find a problem, please post in the comments section, and I'll do what I can. Thanks. Smile | :)

Revision History

  • 7/23/08: Released first version in three versions of .NET.
  • 7/28/08: Added the Application.ApplicationExit event to make sure hooks stop.
  • 8/8/08: Got rid of the debug code in the Macro example, added the MouseWheel method to the MouseSimulator class, and got rid of the duplicate MousePoint class used in MouseSimulator.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Brian Geiman
Software Developer GEA Refrigeration
United States United States
No Biography provided

Comments and Discussions

 
Questionremote desckTop Pin
atefeh shahidifard at 24-Jan-15 9:23
memberatefeh shahidifard24-Jan-15 9:23 
QuestionMouseButton 4 and 5 Pin
daffyduck187 at 9-Jan-15 12:28
memberdaffyduck1879-Jan-15 12:28 
QuestionAlt gr Pin
Member 11146337 at 11-Oct-14 13:37
memberMember 1114633711-Oct-14 13:37 
QuestionSaving mouse keyboard events into file - and reply them later Pin
Member 11094636 at 22-Sep-14 20:32
memberMember 1109463622-Sep-14 20:32 
QuestionKeyDown's behavior is the same as KeyPress! Pin
Hashem AL-Rifai at 22-Jul-14 23:54
memberHashem AL-Rifai22-Jul-14 23:54 
SuggestionMessage Automatically Removed Pin
at 18-Jul-14 4:04
memberMember 1093440018-Jul-14 4:04 
QuestionRecording in host application Pin
caesarh at 12-May-14 4:49
membercaesarh12-May-14 4:49 
Questionx86 and x64 Problem Pin
gerd87 at 23-Mar-14 5:57
membergerd8723-Mar-14 5:57 
QuestionThis cannot work in a console Pin
Spaun1991 at 15-Jan-14 7:52
memberSpaun199115-Jan-14 7:52 
QuestionGreat job. Pin
Member 10465770 at 7-Jan-14 20:32
memberMember 104657707-Jan-14 20:32 
GeneralSave / load macro - a solution [modified] Pin
Member 10347603 at 1-Nov-13 6:02
memberMember 103476031-Nov-13 6:02 
GeneralRe: Save / load macro - a solution Pin
walter iermano at 23-Apr-15 13:16
memberwalter iermano23-Apr-15 13:16 
QuestionSHIFT+END Not work Pin
Member 4615977 at 5-Oct-13 4:09
memberMember 46159775-Oct-13 4:09 
QuestionNot working in .NET 4 ! Pin
Member 10197655 at 18-Sep-13 22:53
memberMember 1019765518-Sep-13 22:53 
AnswerRe: Not working in .NET 4 ! Pin
Shashi_zen at 21-Sep-13 2:57
memberShashi_zen21-Sep-13 2:57 
AnswerRe: Not working in .NET 4 ! Pin
thanapon26 at 20-Mar-14 20:09
memberthanapon2620-Mar-14 20:09 
Questionplay macro in game Pin
ragil.sa at 21-Aug-13 8:13
memberragil.sa21-Aug-13 8:13 
QuestionHow to convert char to it's corresponding KeyCode value? Pin
HallurA at 23-Jun-13 15:26
memberHallurA23-Jun-13 15:26 
QuestionReplication Does not work Pin
Member 9927463 at 2-Apr-13 4:11
memberMember 99274632-Apr-13 4:11 
Questionmouse control Pin
qazxqazx at 11-Mar-13 7:30
memberqazxqazx11-Mar-13 7:30 
QuestionMouseKeyboardLibrary program Pin
rajatdas2005 at 8-Jan-13 3:01
memberrajatdas20058-Jan-13 3:01 
QuestionShif+Left Pin
Member 9670609 at 10-Dec-12 3:33
memberMember 967060910-Dec-12 3:33 
GeneralMy vote of 5 Pin
dinhcongthang at 3-Dec-12 15:31
memberdinhcongthang3-Dec-12 15:31 
GeneralMy vote of 5 Pin
jfln at 21-Nov-12 4:32
memberjfln21-Nov-12 4:32 
A good, small library that does exactly what it says. Great documentation too. Thanks!
GeneralGreat Code - Great Work Pin
Viraj Doshi at 2-Nov-12 0:22
memberViraj Doshi2-Nov-12 0:22 
GeneralVery Good! Pin
oiabc at 7-Sep-12 5:54
memberoiabc7-Sep-12 5:54 
QuestionMouseDown and Move Pin
arpego at 4-Aug-12 15:34
memberarpego4-Aug-12 15:34 
GeneralMy vote of 5 Pin
csharpbd at 3-Jul-12 2:20
membercsharpbd3-Jul-12 2:20 
GeneralMy vote of 5 Pin
ProEnggSoft at 7-Mar-12 19:44
memberProEnggSoft7-Mar-12 19:44 
Questionproblem with right button Pin
irFan91 at 7-Feb-12 14:38
memberirFan917-Feb-12 14:38 
QuestionProblem with Ctrl Pin
kirahvi at 1-Feb-12 1:23
memberkirahvi1-Feb-12 1:23 
AnswerRe: Problem with Ctrl Pin
Aderele Joseph at 23-Oct-12 14:48
memberAderele Joseph23-Oct-12 14:48 
QuestionNice work! Pin
Roy Barina at 27-Jan-12 10:55
memberRoy Barina27-Jan-12 10:55 
QuestionRequest Pin
mschotamaster at 16-Dec-11 18:12
membermschotamaster16-Dec-11 18:12 
Questionhow can we save the recorded macro? Pin
mschotamaster at 16-Dec-11 18:10
membermschotamaster16-Dec-11 18:10 
QuestionGlobal Macro Record Example - Not responding itself Pin
Pham Van Luan at 8-Dec-11 5:13
memberPham Van Luan8-Dec-11 5:13 
QuestionGlobal Mouse and Keyboard Library Pin
shfitythrower at 6-Dec-11 7:35
membershfitythrower6-Dec-11 7:35 
QuestionSolve my Problem Please Pin
shfitythrower at 6-Dec-11 7:32
membershfitythrower6-Dec-11 7:32 
AnswerRe: Solve my Problem Please Pin
Pham Van Luan at 24-Dec-11 21:57
memberPham Van Luan24-Dec-11 21:57 
GeneralRe: Solve my Problem Please Pin
shfitythrower at 15-Jan-12 20:43
membershfitythrower15-Jan-12 20:43 
Questionproblem when using with the float data type [modified] Pin
irFan91 at 27-Oct-11 22:53
memberirFan9127-Oct-11 22:53 
QuestionCan't run normally in .net4.0 Pin
hambor at 29-Aug-11 4:24
memberhambor29-Aug-11 4:24 
AnswerRe: Can't run normally in .net4.0 Pin
AuspexPT at 19-Nov-11 10:40
memberAuspexPT19-Nov-11 10:40 
QuestionUsing this to create a Keyboard Layout Pin
vinodonly at 8-Aug-11 3:37
membervinodonly8-Aug-11 3:37 
GeneralGreat work Pin
izayoikagami at 29-Jul-11 7:31
memberizayoikagami29-Jul-11 7:31 
Questionto use this code in .NET 4.0 Pin
BillWoodruff at 5-Jul-11 19:50
memberBillWoodruff5-Jul-11 19:50 
QuestionHow can I press hotkey Ctrl + C and double click Pin
lampv01203 at 27-Jun-11 7:44
memberlampv0120327-Jun-11 7:44 
GeneralIt's not work! Pin
rakkang at 18-Jun-11 3:20
memberrakkang18-Jun-11 3:20 
GeneralRe: It's not work! Pin
outerhell at 28-Jan-14 0:44
memberouterhell28-Jan-14 0:44 
GeneralMy vote of 5 Pin
jo le serb at 18-Jun-11 1:59
memberjo le serb18-Jun-11 1:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150427.1 | Last Updated 8 Aug 2008
Article Copyright 2008 by Brian Geiman
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid