Low Level Global Keyboard Hook / Sink in C# .NET

Getting user input from the keyboard is easy in .NET, in either a WPF, or Windows Forms application. However, it’s not as easy as it might seem if you need to worry about the keyboard input focus being lost to another application or the desktop itself, or anything at all that isn’t your application for that matter!

Do you want to capture keyboard input in anything but a visible input field in your application? If you need to reliably capture whatever is being pressed on the keyboard no matter what has focus on the machine, you need to be listening for keyboard input at a “low-level”, that is, a lower level than your application, a lower level then the .NET framework itself in fact. That’s where p/invoke and low level keyboard hooking comes in…

P/Invoke and the [DLLImport] Attribute: Your low-level-windows-to-.NET liaison!

You will need to use some native, unmanaged Windows methods out of the Windows User32.DLL. That’s what the [DLLImport] attribute and p/invoke are for.

  • First: Know and understand the methods you will use, by visiting the appropriate article on MSDN.
  • Next: find the correct translation of the native User32 method to it’s C# and/or VB.NET signature.
  • For example: to access keyboard events at a low level, one of the native windows methods we will need is: SetWindowsHookEx, whose translation to .NET managed memory land via the C# language can be found at: setwindowshookex (user32).

Armed with your new low-level knowledge, add the methods you need to your application and put them to good and careful use! What I’ve created as an example, in the code below, is a class which encapsulates the low-level keyboard hooking. An instance of this type can broadcast an event containing the key pressed, every time anything is pressed on the keyboard, whether the input is done in the host application or not.

/* 
Copyright (c) 2019 dylansweb.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Input;
 
namespace DesktopWPFAppLowLevelKeyboardHook
{
    public class LowLevelKeyboardListener
    {
        private const int WH_KEYBOARD_LL = 13;
        private const int WM_KEYDOWN = 0x0100;
        private const int WM_SYSKEYDOWN = 0x0104;
 
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
 
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);
 
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
 
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);
 
        public delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
 
        public event EventHandler<KeyPressedArgs> OnKeyPressed;
 
        private LowLevelKeyboardProc _proc;
        private IntPtr _hookID = IntPtr.Zero;
 
        public LowLevelKeyboardListener()
        {
            _proc = HookCallback;
        }
 
        public void HookKeyboard()
        {
            _hookID = SetHook(_proc);
        }
 
        public void UnHookKeyboard()
        {
            UnhookWindowsHookEx(_hookID);
        }
 
        private IntPtr SetHook(LowLevelKeyboardProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
            }
        }
 
        private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_SYSKEYDOWN)
            {
                int vkCode = Marshal.ReadInt32(lParam);
 
                if (OnKeyPressed != null) { OnKeyPressed(this, new KeyPressedArgs(KeyInterop.KeyFromVirtualKey(vkCode))); }
            }
 
            return CallNextHookEx(_hookID, nCode, wParam, lParam);
        }
    }
 
    public class KeyPressedArgs : EventArgs
    {
        public Key KeyPressed { get; private set; }
 
        public KeyPressedArgs(Key key)
        {
            KeyPressed = key;
        }
    }
}

And here’s the MainWindow.cs of a WPF desktop application that simply demonstrates using our awesome keyboard hook by blindly writing out to a text box, every key-press you do on the keyboard, regardless of “where” you are actually typing:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
 
namespace DesktopWPFAppLowLevelKeyboardHook
{
    public partial class MainWindow : Window
    {
        private LowLevelKeyboardListener _listener;
 
        public MainWindow()
        {
            InitializeComponent();
        }
 
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            _listener = new LowLevelKeyboardListener();
            _listener.OnKeyPressed += _listener_OnKeyPressed;
 
            _listener.HookKeyboard();
        }
 
        void _listener_OnKeyPressed(object sender, KeyPressedArgs e)
        {
            this.textBox_DisplayKeyboardInput.Text += e.KeyPressed.ToString();
        }
 
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            _listener.UnHookKeyboard();
        }
    }
}

A quick test of the reliability of this method for keyboard input capture is to do the following: Open notepad with the app open as well, and start typing in notepad, or even the address bar of your web browser…no matter where or what you type, the keys will be written to the text-box because, it is being spoon-fed by your shiny new low-level keyboard listener 🙂 – Happy Coding!