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 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 was working only when an application was 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
to WH_MOUSE_LL
in the MSDN example and it worked.
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 there is an unmanaged DLL in C++ that is a main part of this solution. This unmanaged DLL in C++ and a number of classes make it complicated to integrate it in my own tiny application.
Using the code
To use this class in your application, you need just to create an instance of it and hang on events you would like to process. Hooks are automatically installed when the object created, but you can stop and start listening using appropriate public methods.
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:
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());
}