Skip to content

Instantly share code, notes, and snippets.

Created Sep 14, 2012
Embed
What would you like to do?
using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Runtime.InteropServices;
class KeyDownPreview
{
#region Initialization
private IntPtr Hook = IntPtr.Zero;
private event KeyEventHandler KeyDown, KeyUp;
[DllImport("user32.dll")]
static extern IntPtr SetWindowsHookEx(int idHook, KeyboardHookProcess callback, IntPtr hInstance, uint threadId);
[DllImport("user32.dll")]
static extern bool UnhookWindowsHookEx(IntPtr hInstance);
[DllImport("user32.dll")]
static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref KeyboardHookStruct lParam);
[DllImport("kernel32.dll")]
static extern IntPtr LoadLibrary(string lpFileName);
public struct KeyboardHookStruct
{
public int KeyCode, ScanCode, Flags, Time, DwExtraInfo;
}
private delegate int KeyboardHookProcess(int code, int wParam, ref KeyboardHookStruct lParam);
private const int WH_KEYBOARD_LL = 13, WM_KEYDOWN = 0x100, WM_KEYUP = 0x101, WM_SYSKEYDOWN = 0x104, WM_SYSKEYUP = 0x105;
#endregion
#region Main
public KeyDownPreview()
{
var hInstance = LoadLibrary("User32");
Hook = SetWindowsHookEx(WH_KEYBOARD_LL, HookProccess, hInstance, 0);
}
~KeyDownPreview()
{
UnhookWindowsHookEx(Hook);
}
public int HookProccess(int code, int wParam, ref KeyboardHookStruct lParam)
{
if (code >= 0)
{
var kea = new KeyEventArgs((Keys)lParam.KeyCode);
if ((wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) && KeyDown != null)
{
KeyDown(this, kea);
}
else if ((wParam == WM_KEYUP || wParam == WM_SYSKEYUP) && KeyUp != null)
{
KeyUp(this, kea);
}
if (kea.Handled)
return 1;
}
return CallNextHookEx(Hook, code, wParam, ref lParam);
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment