InputHandlers NuGet

This NuGet package allows for two things:
  1. Hook to a keyboard event across the system, and trigger an event informing of the pressed/released key along with modifier-keys relevant.
  2. Send text as if typed from the keyboard to the currently keyboard focused application.

Please note: Due to an intended limitation set by Microsoft Windows (TM), when in the Windows login screen Windows deliberately ignores any keyboard/mouse hooks set, so text sent to the password textbox on that screen - will not be typed out.

Creating a system-wide keyboard hook

First, let's hook to keyboard events across the system:
using InputHandlers.KeyboardHandling;
using System.Windows.Forms;

void Main()
{
    Keys lastKey = Keys.None;
    KeyboardGlobalInterceptor.KeyDown +=
        (sender, args) =>
        {
            if (lastKey != args.KeyData)
            {
                Console.WriteLine("Pressed {0}", args.KeyData);
            }
        };

    KeyboardGlobalInterceptor.ApplyKeyboardHook();
}

KeyboardGlobalInterceptor.KeyDown() event is triggered once there's a key pressed event. The args parameter of type Keys contains the pressed key and modifiers. Check out also the KeyPressed and KeyReleased events.
You can also use the property KeyboardGlobalInterceptor.CurrentlyPressedExtendedKeys to just read the currently pressed modifier keys.
The KeyboardGlobalInterceptor.ApplyKeyboardHook() method is blocking. Once run, it creates the hook and does not return until terminating the application.

You can bind and unbind the keyboard hook asynchronously using the KeyboardGlobalInterceptor.ApplyAsyncKeyboardHook() and the KeyboardGlobalInterceptor.DenyAsyncKeyboardHook() methods accordingly. Note that these must be run from the same context.

void Main()
{
    Keys lastKey = Keys.None;
    KeyboardGlobalInterceptor.KeyDown +=
        (sender, args) =>
        {
            if (lastKey != args.KeyData)
            {
                Console.WriteLine("Pressed {0}", args.KeyData);
            }
        };

    KeyboardGlobalInterceptor.ApplyAsyncKeyboardHook();
    Console.WriteLine("Keyboard hook binded.");
        
    Console.ReadLine(); // Focus on some other window to see the keys typed
    KeyboardGlobalInterceptor.DenyAsyncKeyboardHook();
    Console.WriteLine("Keyboard hook unbinded.");
}

Sending text to be typed in the currently focused window

The KeyboardSynth static class exports an API to allow single keyboard strokes or the typing of a whole string message using its Type() overload methods. It also provides Press() and Release() methods to simulate a more granular keyboard behavior.
KeyboardSynth.Type("My message to type");

Note that the Type method can insert wait interval between strokes, and even temporarily disable keyboard hooks set by the same context.

Code regarding keyboard and mouse handling in this package is based on the TestApi project in CodePlex.

Last edited Dec 7, 2014 at 4:10 PM by adi3shilo, version 10