Hello everyone,
In this post i am sharing my personal global keyboard hook.
What is a global keyboard hook?
A global keyboard hook enables you to capture any key press.
No matter if your application is in the front or back.
Thus the meaning global.
I have simplified the class for easy usage.
And made the code as short as possible.
Thus i do not use exception handling and so on.
Right so how to use this code?
There are 3 options you can use.
1: KeyBoardHook.HandleCallBack = YourVoidName;
This is the void where you can interact with the key presses.
The void should use key press event keys.
The namespace for keys is in System.Windows.Forms.
For example,
internal void YourVoidName(Keys PressedKey)
{
//Do whatever you want with the keys send.
}
2: KeyBoardHook.Start();
This will start the hook.
3: KeyBoardHook.Stop();
This will disable the keyboard hook.
So with the above simple functions you can use a global keyboard hook in your application.
Below is the class for keyboard hook.
Enjoy.
#region Imports
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
#endregion
class KeyBoardHook
{
#region DLLImports
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, KeyBoardProcess lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
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);
#endregion
#region Delegates
private delegate IntPtr KeyBoardProcess(int nCode, IntPtr wParam, IntPtr lParam);
internal delegate void MainCallBack(System.Windows.Forms.Keys e);
#endregion
#region Fields
private static KeyBoardProcess KeyBoardCallBack = HookCallback;
internal static MainCallBack CallBackHandler = null;
private static IntPtr KeyBoardHookID = IntPtr.Zero;
private const int WinHookL = 13;
private const int WinHookKeyDown = 0x0100;
#endregion
#region Start Hook
internal static void Start()
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
KeyBoardHookID = SetWindowsHookEx(WinHookL, KeyBoardCallBack, GetModuleHandle(curModule.ModuleName), 0);
}
#endregion
#region Stop Hook
internal static void Stop()
{
UnhookWindowsHookEx(KeyBoardHookID);
}
#endregion
#region CallBack
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WinHookKeyDown)
CallBackHandler((System.Windows.Forms.Keys)Marshal.ReadInt32(lParam));
return CallNextHookEx(KeyBoardHookID, nCode, wParam, lParam);
}
#endregion
}