Skip to content

Instantly share code, notes, and snippets.

Created September 14, 2012 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/3723328 to your computer and use it in GitHub Desktop.
Save anonymous/3723328 to your computer and use it in GitHub Desktop.
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