Click here to Skip to main content
15,905,508 members
Articles / Programming Languages / C#

Processing Global Mouse and Keyboard Hooks in C#

Rate me:
Please Sign up or sign in to vote.
4.97/5 (614 votes)
31 Aug 2011CPOL6 min read 17.2M   218.6K   1K   1.4K
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.

NEWS

This article was posted in 2004 and updated in 2006 and 2008. During all this time until now I receive a lot of positive feedback and recommendations. There where also many useful contributions which where usually posted as code snippets in forum. Now instead of publishing yet another version on my own I decided to ask you all to actively participate. So please be enthusiastic, feel free to join the project at globalmousekeyhook.codeplex.com

You can help by:
  • Contributing code.
  • Creating issue items requesting additional features or reporting defects.
  • Voting for features and fixes you are interested in.
  • Testing the component in different environments.
  • Writing developer documentation.

This will us also allow to keep this original article up to date.

Thank you all for all your great comments on CodeProject forum and looking forward for your brilliant contributions at globalmousekeyhook.codeplex.com

Introduction

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 events with KeyEventArgs and MouseEventArgs, 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 are WH_KEYBOARD_LL and WH_MOUSE_LL hooks that can be installed globally. So, I have basically replaced WH_MOUSE with WH_MOUSE_LL in the MSDN example, and it works.

The second step was to extract the information received into a .NET EventArgs and 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 is a component named GlobalEventProvider inside the assembly Gma.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 by the static class HookManager. Note that the sender object in events is always null.

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 would like to process. Hooks are automatically installed when the object is created, but you can stop and start listening using appropriate public methods.

C#
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:

C#
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 included in event arguments
  • Better exception handling
  • Cancellation of keyboard events using the Handled property 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 calling the SetWindowsHookEx. Why? Is it a problem of .NET 2.0?

Answer

The compiled release version works well so that cannot be a .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 set the e.Handled property to true in 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...

C#
private const int WH_MOUSE = 7;
private const int WH_KEYBOARD = 2;

... everywhere, instead of:

C#
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 hooks WH_MOUSE_LL and WH_KEYBOARD_LL can 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 clicking the x button 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+A?

Answer

You'll have to track which keys have gone down but not up. Only the most recently pressed key keeps sending KeyDown messages, but the others will still send a KeyUp when released. So if you make three flags IsCtrlDown, IsShiftDown, and IsADown, and set them to true at KeyDown and false at KeyUp, 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 file UserActivityHook.cs can be used without any changes, in a Visual Studio 2003 .NET 1.1 project.

License

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


Written By
Software Developer
Germany Germany
Tweeter: @gmamaladze
Google+: gmamaladze
Blog: gmamaladze.wordpress.com

Comments and Discussions

 
Questionhow to catch a event like shift+leftclick ? Pin
Pinto27-Jul-08 0:05
Pinto27-Jul-08 0:05 
JokeRe: how to catch a event like shift+leftclick ? Pin
George Mamaladze31-Oct-08 12:35
George Mamaladze31-Oct-08 12:35 
QuestionHow to make debugging work in VS2008 (express) with these hooks. Pin
GhediPunk16-Jul-08 19:28
GhediPunk16-Jul-08 19:28 
AnswerRe: How to make debugging work in VS2008 (express) with these hooks. Pin
master20226-Aug-08 23:14
master20226-Aug-08 23:14 
QuestionMemory Leak? Pin
cflux11-Jul-08 11:48
cflux11-Jul-08 11:48 
QuestionHow do I catch key combinations like Ctrl+Shift+A? Pin
countnazgul11-Jul-08 5:26
countnazgul11-Jul-08 5:26 
AnswerRe: How do I catch key combinations like Ctrl+Shift+A? Pin
GhediPunk16-Jul-08 19:39
GhediPunk16-Jul-08 19:39 
QuestionHow to Convert Forms Key to Wpf Key? Pin
Anandakumar30-Jun-08 1:36
Anandakumar30-Jun-08 1:36 
Hi,
In the above key hooking method will using Forms Keys. But I'm using WPF Sytem.Windows.Input.Key.
I converted all forms key to Wpf key. It will through Exceptions in some places Where key code above 171 How can i convert forms key to Wpf(Forms key containg enum Member 0-255 and special but wpf contains only 0 to 171)

My Converted Code Is
#endregion Page Header
using System;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Threading;
using System.ComponentModel;
using System.Windows.Input;
using System.Diagnostics;
using System.Windows;
using System.Windows.Media;

namespace LnT.ULS26.UserConsole
{
/// <summary>
/// This class allows you to tap keyboard and mouse and / or to detect their activity even when an
/// application runes in background or does not have any user interface at all. This class raises
/// common .NET events with KeyEventArgs and MouseEventArgs so you can easily retrive any information you need.
/// </summary>
public class UserActivityHook
{
#region Windows structure definitions

/// <summary>
/// The POINT structure defines the x- and y- coordinates of a point.
/// </summary>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/rectangl_0tiq.asp
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
private class POINT
{
/// <summary>
/// Specifies the x-coordinate of the point.
/// </summary>
public int x;
/// <summary>
/// Specifies the y-coordinate of the point.
/// </summary>
public int y;
}

/// <summary>
/// The MOUSEHOOKSTRUCT structure contains information about a mouse event passed to a WH_MOUSE hook procedure, MouseProc.
/// </summary>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookstructures/cwpstruct.asp
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
private class MouseHookStruct
{
/// <summary>
/// Specifies a POINT structure that contains the x- and y-coordinates of the cursor, in screen coordinates.
/// </summary>
public POINT pt;
/// <summary>
/// Handle to the window that will receive the mouse message corresponding to the mouse event.
/// </summary>
public int hwnd;
/// <summary>
/// Specifies the hit-test value. For a list of hit-test values, see the description of the WM_NCHITTEST message.
/// </summary>
public int wHitTestCode;
/// <summary>
/// Specifies extra information associated with the message.
/// </summary>
public int dwExtraInfo;
}

/// <summary>
/// The MSLLHOOKSTRUCT structure contains information about a low-level keyboard input event.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
private class MouseLLHookStruct
{
/// <summary>
/// Specifies a POINT structure that contains the x- and y-coordinates of the cursor, in screen coordinates.
/// </summary>
public POINT pt;
/// <summary>
/// If the message is WM_MOUSEWHEEL, the high-order word of this member is the wheel delta.
/// The low-order word is reserved. A positive value indicates that the wheel was rotated forward,
/// away from the user; a negative value indicates that the wheel was rotated backward, toward the user.
/// One wheel click is defined as WHEEL_DELTA, which is 120.
///If the message is WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK, WM_NCXBUTTONDOWN, WM_NCXBUTTONUP,
/// or WM_NCXBUTTONDBLCLK, the high-order word specifies which X button was pressed or released,
/// and the low-order word is reserved. This value can be one or more of the following values. Otherwise, mouseData is not used.
///XBUTTON1
///The first X button was pressed or released.
///XBUTTON2
///The second X button was pressed or released.
/// </summary>
public int mouseData;
/// <summary>
/// Specifies the event-injected flag. An application can use the following value to test the mouse flags. Value Purpose
///LLMHF_INJECTED Test the event-injected flag.
///0
///Specifies whether the event was injected. The value is 1 if the event was injected; otherwise, it is 0.
///1-15
///Reserved.
/// </summary>
public int flags;
/// <summary>
/// Specifies the time stamp for this message.
/// </summary>
public int time;
/// <summary>
/// Specifies extra information associated with the message.
/// </summary>
public int dwExtraInfo;
}


/// <summary>
/// The KBDLLHOOKSTRUCT structure contains information about a low-level keyboard input event.
/// </summary>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookstructures/cwpstruct.asp
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
private class KeyboardHookStruct
{
/// <summary>
/// Specifies a virtual-key code. The code must be a value in the range 1 to 254.
/// </summary>
public int vkCode;
/// <summary>
/// Specifies a hardware scan code for the key.
/// </summary>
public int scanCode;
/// <summary>
/// Specifies the extended-key flag, event-injected flag, context code, and transition-state flag.
/// </summary>
public int flags;
/// <summary>
/// Specifies the time stamp for this message.
/// </summary>
public int time;
/// <summary>
/// Specifies extra information associated with the message.
/// </summary>
public int dwExtraInfo;
}
#endregion

#region Windows function imports
/// <summary>
/// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
/// You would install a hook procedure to monitor the system for certain types of events. These events
/// are associated either with a specific thread or with all threads in the same desktop as the calling thread.
/// </summary>
/// <param name="idHook">
/// [in] Specifies the type of hook procedure to be installed. This parameter can be one of the following values.
/// </param>
/// <param name="lpfn">
/// [in] Pointer to the hook procedure. If the dwThreadId parameter is zero or specifies the identifier of a
/// thread created by a different process, the lpfn parameter must point to a hook procedure in a dynamic-link
/// library (DLL). Otherwise, lpfn can point to a hook procedure in the code associated with the current process.
/// </param>
/// <param name="hMod">
/// [in] Handle to the DLL containing the hook procedure pointed to by the lpfn parameter.
/// The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by
/// the current process and if the hook procedure is within the code associated with the current process.
/// </param>
/// <param name="dwThreadId">
/// [in] Specifies the identifier of the thread with which the hook procedure is to be associated.
/// If this parameter is zero, the hook procedure is associated with all existing threads running in the
/// same desktop as the calling thread.
/// </param>
/// <returns>
/// If the function succeeds, the return value is the handle to the hook procedure.
/// If the function fails, the return value is NULL. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
/// </remarks>
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern int SetWindowsHookEx(
int idHook,
HookProc lpfn,
IntPtr hMod,
int dwThreadId);

/// <summary>
/// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
/// </summary>
/// <param name="idHook">
/// [in] Handle to the hook to be removed. This parameter is a hook handle obtained by a previous call to SetWindowsHookEx.
/// </param>
/// <returns>
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
/// </remarks>
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern int UnhookWindowsHookEx(int idHook);

/// <summary>
/// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
/// A hook procedure can call this function either before or after processing the hook information.
/// </summary>
/// <param name="idHook">Ignored.</param>
/// <param name="nCode">
/// [in] Specifies the hook code passed to the current hook procedure.
/// The next hook procedure uses this code to determine how to process the hook information.
/// </param>
/// <param name="wParam">
/// [in] Specifies the wParam value passed to the current hook procedure.
/// The meaning of this parameter depends on the type of hook associated with the current hook chain.
/// </param>
/// <param name="lParam">
/// [in] Specifies the lParam value passed to the current hook procedure.
/// The meaning of this parameter depends on the type of hook associated with the current hook chain.
/// </param>
/// <returns>
/// This value is returned by the next hook procedure in the chain.
/// The current hook procedure must also return this value. The meaning of the return value depends on the hook type.
/// For more information, see the descriptions of the individual hook procedures.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
/// </remarks>
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
private static extern int CallNextHookEx(
int idHook,
int nCode,
int wParam,
IntPtr lParam);

/// <summary>
/// The CallWndProc hook procedure is an application-defined or library-defined callback
/// function used with the SetWindowsHookEx function. The HOOKPROC type defines a pointer
/// to this callback function. CallWndProc is a placeholder for the application-defined
/// or library-defined function name.
/// </summary>
/// <param name="nCode">
/// [in] Specifies whether the hook procedure must process the message.
/// If nCode is HC_ACTION, the hook procedure must process the message.
/// If nCode is less than zero, the hook procedure must pass the message to the
/// CallNextHookEx function without further processing and must return the
/// value returned by CallNextHookEx.
/// </param>
/// <param name="wParam">
/// [in] Specifies whether the message was sent by the current thread.
/// If the message was sent by the current thread, it is nonzero; otherwise, it is zero.
/// </param>
/// <param name="lParam">
/// [in] Pointer to a CWPSTRUCT structure that contains details about the message.
/// </param>
/// <returns>
/// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
/// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx
/// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC
/// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook
/// procedure does not call CallNextHookEx, the return value should be zero.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/callwndproc.asp
/// </remarks>
private delegate int HookProc(int nCode, int wParam, IntPtr lParam);

/// <summary>
/// The ToAscii function translates the specified virtual-key code and keyboard
/// state to the corresponding character or characters. The function translates the code
/// using the input language and physical keyboard layout identified by the keyboard layout handle.
/// </summary>
/// <param name="uVirtKey">
/// [in] Specifies the virtual-key code to be translated.
/// </param>
/// <param name="uScanCode">
/// [in] Specifies the hardware scan code of the key to be translated.
/// The high-order bit of this value is set if the key is up (not pressed).
/// </param>
/// <param name="lpbKeyState">
/// [in] Pointer to a 256-byte array that contains the current keyboard state.
/// Each element (byte) in the array contains the state of one key.
/// If the high-order bit of a byte is set, the key is down (pressed).
/// The low bit, if set, indicates that the key is toggled on. In this function,
/// only the toggle bit of the CAPS LOCK key is relevant. The toggle state
/// of the NUM LOCK and SCROLL LOCK keys is ignored.
/// </param>
/// <param name="lpwTransKey">
/// [out] Pointer to the buffer that receives the translated character or characters.
/// </param>
/// <param name="fuState">
/// [in] Specifies whether a menu is active. This parameter must be 1 if a menu is active, or 0 otherwise.
/// </param>
/// <returns>
/// If the specified key is a dead key, the return value is negative. Otherwise, it is one of the following values.
/// Value Meaning
/// 0 The specified virtual key has no translation for the current state of the keyboard.
/// 1 One character was copied to the buffer.
/// 2 Two characters were copied to the buffer. This usually happens when a dead-key character
/// (accent or diacritic) stored in the keyboard layout cannot be composed with the specified
/// virtual key to form a single character.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/toascii.asp
/// </remarks>
[DllImport("user32")]
private static extern int ToAscii(
int uVirtKey,
int uScanCode,
byte[] lpbKeyState,
byte[] lpwTransKey,
int fuState);

/// <summary>
/// The GetKeyboardState function copies the status of the 256 virtual keys to the
/// specified buffer.
/// </summary>
/// <param name="pbKeyState">
/// [in] Pointer to a 256-byte array that contains keyboard key states.
/// </param>
/// <returns>
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/toascii.asp
/// </remarks>
[DllImport("user32")]
private static extern int GetKeyboardState(byte[] pbKeyState);

[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern short GetKeyState(int vKey);

#endregion

#region Windows constants

//values from Winuser.h in Microsoft SDK.
/// <summary>
/// Windows NT/2000/XP: Installs a hook procedure that monitors low-level mouse input events.
/// </summary>
private const int WH_MOUSE_LL = 14;
/// <summary>
/// Windows NT/2000/XP: Installs a hook procedure that monitors low-level keyboard input events.
/// </summary>
private const int WH_KEYBOARD_LL = 13;

/// <summary>
/// Installs a hook procedure that monitors mouse messages. For more information, see the MouseProc hook procedure.
/// </summary>
private const int WH_MOUSE = 7;
/// <summary>
/// Installs a hook procedure that monitors keystroke messages. For more information, see the KeyboardProc hook procedure.
/// </summary>
private const int WH_KEYBOARD = 2;

/// <summary>
/// The WM_MOUSEMOVE message is posted to a window when the cursor moves.
/// </summary>
private const int WM_MOUSEMOVE = 0x200;
/// <summary>
/// The WM_LBUTTONDOWN message is posted when the user presses the left mouse button
/// </summary>
private const int WM_LBUTTONDOWN = 0x201;
/// <summary>
/// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button
/// </summary>
private const int WM_RBUTTONDOWN = 0x204;
/// <summary>
/// The WM_MBUTTONDOWN message is posted when the user presses the middle mouse button
/// </summary>
private const int WM_MBUTTONDOWN = 0x207;
/// <summary>
/// The WM_LBUTTONUP message is posted when the user releases the left mouse button
/// </summary>
private const int WM_LBUTTONUP = 0x202;
/// <summary>
/// The WM_RBUTTONUP message is posted when the user releases the right mouse button
/// </summary>
private const int WM_RBUTTONUP = 0x205;
/// <summary>
/// The WM_MBUTTONUP message is posted when the user releases the middle mouse button
/// </summary>
private const int WM_MBUTTONUP = 0x208;
/// <summary>
/// The WM_LBUTTONDBLCLK message is posted when the user double-clicks the left mouse button
/// </summary>
private const int WM_LBUTTONDBLCLK = 0x203;
/// <summary>
/// The WM_RBUTTONDBLCLK message is posted when the user double-clicks the right mouse button
/// </summary>
private const int WM_RBUTTONDBLCLK = 0x206;
/// <summary>
/// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button
/// </summary>
private const int WM_MBUTTONDBLCLK = 0x209;
/// <summary>
/// The WM_MOUSEWHEEL message is posted when the user presses the mouse wheel.
/// </summary>
private const int WM_MOUSEWHEEL = 0x020A;

/// <summary>
/// The WM_KEYDOWN message is posted to the window with the keyboard focus when a nonsystem
/// key is pressed. A nonsystem key is a key that is pressed when the ALT key is not pressed.
/// </summary>
private const int WM_KEYDOWN = 0x100;
/// <summary>
/// The WM_KEYUP message is posted to the window with the keyboard focus when a nonsystem
/// key is released. A nonsystem key is a key that is pressed when the ALT key is not pressed,
/// or a keyboard key that is pressed when a window has the keyboard focus.
/// </summary>
private const int WM_KEYUP = 0x101;
/// <summary>
/// The WM_SYSKEYDOWN message is posted to the window with the keyboard focus when the user
/// presses the F10 key (which activates the menu bar) or holds down the ALT key and then
/// presses another key. It also occurs when no window currently has the keyboard focus;
/// in this case, the WM_SYSKEYDOWN message is sent to the active window. The window that
/// receives the message can distinguish between these two contexts by checking the context
/// code in the lParam parameter.
/// </summary>
private const int WM_SYSKEYDOWN = 0x104;
/// <summary>
/// The WM_SYSKEYUP message is posted to the window with the keyboard focus when the user
/// releases a key that was pressed while the ALT key was held down. It also occurs when no
/// window currently has the keyboard focus; in this case, the WM_SYSKEYUP message is sent
/// to the active window. The window that receives the message can distinguish between
/// these two contexts by checking the context code in the lParam parameter.
/// </summary>
private const int WM_SYSKEYUP = 0x105;

private const byte VK_SHIFT = 0x10;
private const byte VK_CAPITAL = 0x14;
private const byte VK_NUMLOCK = 0x90;

#endregion

/// <summary>
/// Creates an instance of UserActivityHook object and sets mouse and keyboard hooks.
/// </summary>
/// <exception cref="Win32Exception">Any windows problem.</exception>
public UserActivityHook(Window sender)
{
Start(sender);
}

/// <summary>
/// Creates an instance of UserActivityHook object and installs both or one of mouse and/or keyboard hooks and starts rasing events
/// </summary>
/// <param name="InstallMouseHook"><b>true</b> if mouse events must be monitored</param>
/// <param name="InstallKeyboardHook"><b>true</b> if keyboard events must be monitored</param>
/// <exception cref="Win32Exception">Any windows problem.</exception>
/// <remarks>
/// To create an instance without installing hooks call new UserActivityHook(false, false)
/// </remarks>
public UserActivityHook(bool InstallMouseHook, bool InstallKeyboardHook,Window sender)
{
Start(InstallMouseHook, InstallKeyboardHook,sender);
}

/// <summary>
/// Destruction.
/// </summary>
~UserActivityHook()
{
//uninstall hooks and do not throw exceptions
Stop(true, true, false);
}

/// <summary>
/// Occurs when the user moves the mouse, presses any mouse button or scrolls the wheel
/// </summary>
public event MouseEventHandler OnMouseActivity;
/// <summary>
/// Occurs when the user presses a key
/// </summary>
public event KeyEventHandler KeyDown;
/// <summary>
/// Occurs when the user presses and releases
/// </summary>
//public event KeyPressEventHandler KeyPress;
/// <summary>
/// Occurs when the user releases a key
/// </summary>
public event KeyEventHandler KeyUp;


/// <summary>
/// Stores the handle to the mouse hook procedure.
/// </summary>
private int hMouseHook = 0;
/// <summary>
/// Stores the handle to the keyboard hook procedure.
/// </summary>
private int hKeyboardHook = 0;


/// <summary>
/// Declare MouseHookProcedure as HookProc type.
/// </summary>
private static HookProc MouseHookProcedure;
/// <summary>
/// Declare KeyboardHookProcedure as HookProc type.
/// </summary>
private static HookProc KeyboardHookProcedure;


/// <summary>
/// Installs both mouse and keyboard hooks and starts rasing events
/// </summary>
/// <exception cref="Win32Exception">Any windows problem.</exception>
public void Start(System.Windows.Window send)
{
this.Start(true, true,send);
}
System.Windows.Window sender;
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr GetModuleHandle(string lpModuleName);

/// <summary>
/// Installs both or one of mouse and/or keyboard hooks and starts rasing events
/// </summary>
/// <param name="InstallMouseHook"><b>true</b> if mouse events must be monitored</param>
/// <param name="InstallKeyboardHook"><b>true</b> if keyboard events must be monitored</param>
/// <exception cref="Win32Exception">Any windows problem.</exception>
public void Start(bool InstallMouseHook, bool InstallKeyboardHook,System.Windows.Window send)
{
sender = send;
// install Mouse hook only if it is not installed and must be installed
if (hMouseHook == 0 && InstallMouseHook)
{
// Create an instance of HookProc.
MouseHookProcedure = new HookProc(MouseHookProc);
//install hook
using (Process curProcess = Process.GetCurrentProcess())

using (ProcessModule curModule = curProcess.MainModule)
{

hMouseHook = SetWindowsHookEx(

WH_KEYBOARD_LL, MouseHookProcedure,

GetModuleHandle(curModule.ModuleName), 0);

}
//hMouseHook = SetWindowsHookEx(
// WH_MOUSE_LL,
// MouseHookProcedure,
// Marshal.GetHINSTANCE(
// Assembly.GetExecutingAssembly().GetModules()[0]),
// 0);
//If SetWindowsHookEx fails.
if (hMouseHook == 0)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//do cleanup
Stop(true, false, false);
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}

// install Keyboard hook only if it is not installed and must be installed
if (hKeyboardHook == 0 && InstallKeyboardHook)
{
// Create an instance of HookProc.
KeyboardHookProcedure = new HookProc(KeyboardHookProc);
//install hook
using (Process curProcess = Process.GetCurrentProcess())

using (ProcessModule curModule = curProcess.MainModule)
{

hKeyboardHook = SetWindowsHookEx(

WH_KEYBOARD_LL, KeyboardHookProcedure,

GetModuleHandle(curModule.ModuleName), 0);

}


//hKeyboardHook = SetWindowsHookEx(
// WH_KEYBOARD_LL,
// KeyboardHookProcedure,
// Marshal.GetHINSTANCE(
// Assembly.GetExecutingAssembly().GetModules()[0]),
// 0);
//If SetWindowsHookEx fails.
if (hKeyboardHook == 0)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//do cleanup
Stop(false, true, false);
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
}

/// <summary>
/// Stops monitoring both mouse and keyboard events and rasing events.
/// </summary>
/// <exception cref="Win32Exception">Any windows problem.</exception>
public void Stop()
{
this.Stop(true, true, true);
}

/// <summary>
/// Stops monitoring both or one of mouse and/or keyboard events and rasing events.
/// </summary>
/// <param name="UninstallMouseHook"><b>true</b> if mouse hook must be uninstalled</param>
/// <param name="UninstallKeyboardHook"><b>true</b> if keyboard hook must be uninstalled</param>
/// <param name="ThrowExceptions"><b>true</b> if exceptions which occured during uninstalling must be thrown</param>
/// <exception cref="Win32Exception">Any windows problem.</exception>
public void Stop(bool UninstallMouseHook, bool UninstallKeyboardHook, bool ThrowExceptions)
{
//if mouse hook set and must be uninstalled
if (hMouseHook != 0 && UninstallMouseHook)
{
//uninstall hook
int retMouse = UnhookWindowsHookEx(hMouseHook);
//reset invalid handle
hMouseHook = 0;
//if failed and exception must be thrown
if (retMouse == 0 && ThrowExceptions)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}

//if keyboard hook set and must be uninstalled
if (hKeyboardHook != 0 && UninstallKeyboardHook)
{
//uninstall hook
int retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
//reset invalid handle
hKeyboardHook = 0;
//if failed and exception must be thrown
if (retKeyboard == 0 && ThrowExceptions)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
}


/// <summary>
/// A callback function which will be called every time a mouse activity detected.
/// </summary>
/// <param name="nCode">
/// [in] Specifies whether the hook procedure must process the message.
/// If nCode is HC_ACTION, the hook procedure must process the message.
/// If nCode is less than zero, the hook procedure must pass the message to the
/// CallNextHookEx function without further processing and must return the
/// value returned by CallNextHookEx.
/// </param>
/// <param name="wParam">
/// [in] Specifies whether the message was sent by the current thread.
/// If the message was sent by the current thread, it is nonzero; otherwise, it is zero.
/// </param>
/// <param name="lParam">
/// [in] Pointer to a CWPSTRUCT structure that contains details about the message.
/// </param>
/// <returns>
/// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
/// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx
/// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC
/// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook
/// procedure does not call CallNextHookEx, the return value should be zero.
/// </returns>
private int MouseHookProc(int nCode, int wParam, IntPtr lParam)
{
// if ok and someone listens to our events
if ((nCode >= 0) && (OnMouseActivity != null))
{
//Marshall the data from callback.
MouseLLHookStruct mouseHookStruct = (MouseLLHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseLLHookStruct));

//detect button clicked
MouseButton button = MouseButton.XButton1;
//MouseButtons button = MouseButtons.None;
short mouseDelta = 0;
switch (wParam)
{
case WM_LBUTTONDOWN:
//case WM_LBUTTONUP:
//case WM_LBUTTONDBLCLK:
button = MouseButton.Left;
break;
case WM_RBUTTONDOWN:
//case WM_RBUTTONUP:
//case WM_RBUTTONDBLCLK:
button = MouseButton.Right;
break;
case WM_MOUSEWHEEL:
//If the message is WM_MOUSEWHEEL, the high-order word of mouseData member is the wheel delta.
//One wheel click is defined as WHEEL_DELTA, which is 120.
//(value >> 16) & 0xffff; retrieves the high-order word from the given 32-bit value
mouseDelta = (short)((mouseHookStruct.mouseData >> 16) & 0xffff);
//TODO: X BUTTONS (I havent them so was unable to test)
//If the message is WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK, WM_NCXBUTTONDOWN, WM_NCXBUTTONUP,
//or WM_NCXBUTTONDBLCLK, the high-order word specifies which X button was pressed or released,
//and the low-order word is reserved. This value can be one or more of the following values.
//Otherwise, mouseData is not used.
break;
}

//double clicks
int clickCount = 0;
if (button != MouseButton.XButton1)
{
if (wParam == WM_LBUTTONDBLCLK || wParam == WM_RBUTTONDBLCLK) clickCount = 2;
else clickCount = 1;
}

MouseButtonEventArgs e = new MouseButtonEventArgs(Mouse.PrimaryDevice, 0, button);
//MouseEventArgs e = new MouseEventArgs(
// button,
// clickCount,
// mouseHookStruct.pt.x,
// mouseHookStruct.pt.y,
// mouseDelta);
//raise it
OnMouseActivity(this, e);
}
//call next hook
return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
}

/// <summary>
/// A callback function which will be called every time a keyboard activity detected.
/// </summary>
/// <param name="nCode">
/// [in] Specifies whether the hook procedure must process the message.
/// If nCode is HC_ACTION, the hook procedure must process the message.
/// If nCode is less than zero, the hook procedure must pass the message to the
/// CallNextHookEx function without further processing and must return the
/// value returned by CallNextHookEx.
/// </param>
/// <param name="wParam">
/// [in] Specifies whether the message was sent by the current thread.
/// If the message was sent by the current thread, it is nonzero; otherwise, it is zero.
/// </param>
/// <param name="lParam">
/// [in] Pointer to a CWPSTRUCT structure that contains details about the message.
/// </param>
/// <returns>
/// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
/// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx
/// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC
/// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook
/// procedure does not call CallNextHookEx, the return value should be zero.
/// </returns>
private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
//indicates if any of underlaing events set e.Handled flag
bool handled = false;
//it was ok and someone listens to events
if ((nCode >= 0) && (KeyDown != null || KeyUp != null /*|| KeyPress != null*/))
{
//read structure KeyboardHookStruct at lParam
KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
//raise KeyDown
if (KeyDown != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
{
Key keyData = (Key)MyKeyboardHookStruct.vkCode;
KeyEventArgs e = new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual((Visual)sender), 0, keyData);
//I Got Exception Here
KeyDown(this, e);
handled = handled || e.Handled;
}

// raise KeyPress
//if (KeyPress != null && wParam == WM_KEYDOWN)
//{
// bool isDownShift = ((GetKeyState(VK_SHIFT) & 0x80) == 0x80 ? true : false);
// bool isDownCapslock = (GetKeyState(VK_CAPITAL) != 0 ? true : false);

// byte[] keyState = new byte[256];
// GetKeyboardState(keyState);
// byte[] inBuffer = new byte[2];

// if (ToAscii(MyKeyboardHookStruct.vkCode,
// MyKeyboardHookStruct.scanCode,
// keyState,
// inBuffer,
// MyKeyboardHookStruct.flags) == 1)
// {
// char key = (char)inBuffer[0];
// if ((isDownCapslock ^ isDownShift) && Char.IsLetter(key))
// key = Char.ToUpper(key);

// KeyPressEventArgs e = new KeyPressEventArgs(key);
// KeyPress(this, e);
// handled = handled || e.Handled;
// }
//}

// raise KeyUp
if (KeyUp != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP))
{
Key keyData = (Key)MyKeyboardHookStruct.vkCode;
KeyEventArgs e = new KeyEventArgs(Keyboard.PrimaryDevice, null, 0, keyData);
KeyUp(this, e);
handled = handled || e.Handled;
}

}

//if event handled in application do not handoff to other listeners
if (handled)
return 1;
else
return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}
}
}
GeneralGiorgi Mamaladze Pin
Dr Dre222-Jun-08 22:58
Dr Dre222-Jun-08 22:58 
QuestionHow do I identify which mouse button was released Pin
igorgatis20-Jun-08 1:03
igorgatis20-Jun-08 1:03 
AnswerRe: How do I identify which mouse button was released Pin
igorgatis21-Jun-08 16:45
igorgatis21-Jun-08 16:45 
GeneralAn easier way Pin
timneu2218-Jun-08 1:14
timneu2218-Jun-08 1:14 
GeneralRepositioning Key Cursor Pin
ElDuQuE9-Jun-08 18:34
ElDuQuE9-Jun-08 18:34 
QuestionUsing the class in a "window service" Pin
Mushtaque Nizamani5-Jun-08 14:26
Mushtaque Nizamani5-Jun-08 14:26 
AnswerRe: Using the class in a "window service" Pin
Member 376474126-Jun-08 21:38
Member 376474126-Jun-08 21:38 
GeneralRe: Using the class in a "window service" Pin
Mushtaque Nizamani26-Jun-08 21:47
Mushtaque Nizamani26-Jun-08 21:47 
AnswerRe: Using the class in a "window service" Pin
Member 465789414-Jan-09 11:23
Member 465789414-Jan-09 11:23 
QuestionCapture details of what was clicked Pin
moonmonkey824-May-08 23:01
moonmonkey824-May-08 23:01 
AnswerRe: Capture details of what was clicked Pin
George Mamaladze25-May-08 9:24
George Mamaladze25-May-08 9:24 
GeneralRe: Capture details of what was clicked Pin
moonmonkey825-May-08 10:04
moonmonkey825-May-08 10:04 
GeneralApplication hook does not work Pin
Zodzetrick23-May-08 1:10
Zodzetrick23-May-08 1:10 
GeneralRe: Application hook does not work Pin
George Mamaladze23-May-08 12:00
George Mamaladze23-May-08 12:00 
GeneralRe: Application hook does not work Pin
Zodzetrick24-May-08 2:29
Zodzetrick24-May-08 2:29 
QuestionWhile WH_MOUSE not global hook? Pin
minhvc18-May-08 23:32
minhvc18-May-08 23:32 
Questionhow to save key strokes to a text file and make it invisible Pin
abbmallesh17-May-08 3:52
abbmallesh17-May-08 3:52 

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

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