Click here to Skip to main content
11,478,619 members (63,897 online)
Click here to Skip to main content

Global Mouse and Keyboard Library

, 8 Aug 2008 CPOL 244.2K 16.6K 300
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

 
AnswerRe: Solve my Problem Please Pin
Pham Van Luan24-Dec-11 21:57
memberPham Van Luan24-Dec-11 21:57 
GeneralRe: Solve my Problem Please Pin
shfitythrower15-Jan-12 20:43
membershfitythrower15-Jan-12 20:43 
Questionproblem when using with the float data type [modified] Pin
irFan9127-Oct-11 22:53
memberirFan9127-Oct-11 22:53 
QuestionCan't run normally in .net4.0 Pin
hambor29-Aug-11 4:24
memberhambor29-Aug-11 4:24 
AnswerRe: Can't run normally in .net4.0 Pin
AuspexPT19-Nov-11 10:40
memberAuspexPT19-Nov-11 10:40 
QuestionUsing this to create a Keyboard Layout Pin
vinodonly8-Aug-11 3:37
membervinodonly8-Aug-11 3:37 
GeneralGreat work Pin
izayoikagami29-Jul-11 7:31
memberizayoikagami29-Jul-11 7:31 
Questionto use this code in .NET 4.0 Pin
BillWoodruff5-Jul-11 19:50
memberBillWoodruff5-Jul-11 19:50 
QuestionHow can I press hotkey Ctrl + C and double click Pin
lampv0120327-Jun-11 7:44
memberlampv0120327-Jun-11 7:44 
GeneralIt's not work! Pin
rakkang18-Jun-11 3:20
memberrakkang18-Jun-11 3:20 
GeneralRe: It's not work! Pin
outerhell28-Jan-14 0:44
memberouterhell28-Jan-14 0:44 
GeneralMy vote of 5 Pin
jo le serb18-Jun-11 1:59
memberjo le serb18-Jun-11 1:59 
QuestionCan I use this library in VB.net? Pin
Manindra294-May-11 0:18
memberManindra294-May-11 0:18 
GeneralMy vote of 2 Pin
charles henington19-Apr-11 12:22
membercharles henington19-Apr-11 12:22 
doesn't work
GeneralRe: My vote of 2 Pin
jacob_suibowen3-May-11 14:22
memberjacob_suibowen3-May-11 14:22 
GeneralRe: My vote of 2 Pin
evolaz19-May-11 4:46
memberevolaz19-May-11 4:46 
GeneralRe: My vote of 2 Pin
Aamir Butt3-Sep-11 8:20
memberAamir Butt3-Sep-11 8:20 
QuestionHow to stop play events Pin
StreetMan17-Apr-11 21:34
memberStreetMan17-Apr-11 21:34 
AnswerRe: How to stop play events Pin
charles henington18-Apr-11 12:50
membercharles henington18-Apr-11 12:50 
GeneralMy vote of 5 Pin
Ali Al Omairi(Abu AlHassan)13-Apr-11 20:58
memberAli Al Omairi(Abu AlHassan)13-Apr-11 20:58 
GeneralMy vote of 1 Pin
Ali Al Omairi(Abu AlHassan)13-Apr-11 5:46
memberAli Al Omairi(Abu AlHassan)13-Apr-11 5:46 
GeneralRe: My vote of 1 Pin
charles henington13-Apr-11 6:18
membercharles henington13-Apr-11 6:18 
GeneralRe: My vote of 1 Pin
Ali Al Omairi(Abu AlHassan)13-Apr-11 20:56
memberAli Al Omairi(Abu AlHassan)13-Apr-11 20:56 
GeneralOutstanding Pin
David H Robertson10-Apr-11 4:05
memberDavid H Robertson10-Apr-11 4:05 
QuestionHow to save macros in file???? [modified] Pin
StreetMan31-Mar-11 4:28
memberStreetMan31-Mar-11 4:28 
AnswerRe: How to save macros in file???? Pin
charles henington13-Apr-11 6:29
membercharles henington13-Apr-11 6:29 
Generalnice work Pin
ReymonARG22-Mar-11 19:22
memberReymonARG22-Mar-11 19:22 
GeneralProblem with double chars like ^^ or ~~ Pin
Thiago Burgo17-Mar-11 8:37
memberThiago Burgo17-Mar-11 8:37 
Generalawesome! Pin
Christ Kennedy23-Feb-11 7:45
mvpChrist Kennedy23-Feb-11 7:45 
GeneralSaving List<> of events to a file Pin
Horacio Prada19-Feb-11 12:27
memberHoracio Prada19-Feb-11 12:27 
GeneralSaving the recorded events Pin
Horacio Prada19-Feb-11 5:59
memberHoracio Prada19-Feb-11 5:59 
GeneralExcellent Pin
Kountree29-Dec-10 9:37
memberKountree29-Dec-10 9:37 
GeneralMy vote of 5 Pin
Matthew Dally21-Dec-10 2:38
memberMatthew Dally21-Dec-10 2:38 
GeneralFantastic ! Brilliant solution to a problem ! Pin
vectoraudiouk27-Nov-10 6:20
membervectoraudiouk27-Nov-10 6:20 
GeneralMy vote of 5 Pin
vectoraudiouk27-Nov-10 6:19
membervectoraudiouk27-Nov-10 6:19 
GeneralShift key is not recorded in the macro recorder Pin
Sunny127015-Nov-10 3:47
memberSunny127015-Nov-10 3:47 
GeneralProblem with cyrillic letters Pin
pcpavlov24-Oct-10 0:12
memberpcpavlov24-Oct-10 0:12 
GeneralRe: Problem with cyrillic letters [modified] Pin
pcpavlov24-Oct-10 2:02
memberpcpavlov24-Oct-10 2:02 
GeneralMy vote of 5 Pin
pcpavlov20-Oct-10 23:27
memberpcpavlov20-Oct-10 23:27 
GeneralMy vote of 5 Pin
msp.netdev13-Oct-10 4:41
membermsp.netdev13-Oct-10 4:41 
GeneralMy vote of 5 Pin
dwane_miller1-Oct-10 6:32
memberdwane_miller1-Oct-10 6:32 
QuestionHow do I stop the playback events by pressing a key? Pin
alexmbra12-Sep-10 11:17
memberalexmbra12-Sep-10 11:17 
GeneralFix for .NET 4 Pin
Thiru Thirunavukarasu25-Aug-10 15:04
adminThiru Thirunavukarasu25-Aug-10 15:04 
GeneralRe: Fix for .NET 4 Pin
Mr Pleco4-Sep-10 8:49
memberMr Pleco4-Sep-10 8:49 
GeneralMy vote of 5 Pin
Aslam_Iqbal15-Jul-10 5:08
memberAslam_Iqbal15-Jul-10 5:08 
GeneralSuppressing Pin
Sen Dog31-May-10 3:09
memberSen Dog31-May-10 3:09 
QuestionIt doesn't seems to work in the 2010 beta ver ?? Pin
After-Darkness3-Apr-10 2:50
memberAfter-Darkness3-Apr-10 2:50 
Generale.Handled not working Pin
yannlh15-Mar-10 12:40
memberyannlh15-Mar-10 12:40 
QuestionKeyboard hook not working Pin
xpansive10-Mar-10 13:20
memberxpansive10-Mar-10 13:20 
GeneralTANX Pin
jerviz_764-Feb-10 6:27
memberjerviz_764-Feb-10 6:27 

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
Web04 | 2.8.150520.1 | Last Updated 8 Aug 2008
Article Copyright 2008 by Brian Geiman
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid