class KeyHook
{
[DllImport("user32.dll")]
static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc callback, IntPtr hInstance, uint threadId);
[DllImport("user32.dll")]
static extern bool UnhookWindowsHookEx(IntPtr hInstance);
[DllImport("user32.dll")]
static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, int wParam, IntPtr lParam);
[DllImport("kernel32.dll")]
static extern IntPtr LoadLibrary(string lpFileName);
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
const int WH_KEYBOARD_LL = 13; // Номер глобального LowLevel-хука на клавиатуру
const int WM_KEYDOWN = 0x100; // Сообщения нажатия клавиши
private static LowLevelKeyboardProc _proc = hookProc;
private static IntPtr hhook = IntPtr.Zero;
public static void SetHook()
{
IntPtr hInstance = LoadLibrary("User32");
hhook = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, hInstance, 0);
}
public static void UnHook()
{
UnhookWindowsHookEx(hhook);
}
public static event EventHandler KeyInsert = delegate { };
public static event EventHandler KeyDelete = delegate { };
public static IntPtr hookProc(int code, IntPtr wParam, IntPtr lParam)
{
if (code >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
Form1 f1 = new Form1();
Keys k = (Keys)Marshal.ReadInt32(lParam);
//////ОБРАБОТКА НАЖАТИЯ
if (k == Keys.Insert)
{
KeyInsert(null, new EventArgs());
}
}
return CallNextHookEx(hhook, code, (int)wParam, lParam);
}
}
}