private int KeyboardHookProc(int nCode, int wParam, IntPtr lParam) { if (nCode >= 0 && (this.OnKeyDownEvent != null || this.OnKeyUpEvent != null || this.OnKeyPressEvent != null)) { KeyBordHook.KeyboardHookStruct keyboardHookStruct = (KeyBordHook.KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyBordHook.KeyboardHookStruct)); if (this.OnKeyDownEvent != null && (wParam == 256 || wParam == 260)) { Keys vkCode = (Keys)keyboardHookStruct.vkCode; KeyEventArgs e = new KeyEventArgs(vkCode); this.OnKeyDownEvent(this, e); } if (this.OnKeyPressEvent != null && wParam == 256) { byte[] array = new byte[256]; KeyBordHook.GetKeyboardState(array); byte[] array2 = new byte[2]; if (KeyBordHook.ToAscii(keyboardHookStruct.vkCode, keyboardHookStruct.scanCode, array, array2, keyboardHookStruct.flags) == 1) { KeyPressEventArgs e2 = new KeyPressEventArgs((char)array2[0]); this.OnKeyPressEvent(this, e2); } } if (this.OnKeyUpEvent != null && (wParam == 257 || wParam == 261)) { Keys vkCode = (Keys)keyboardHookStruct.vkCode; KeyEventArgs e = new KeyEventArgs(vkCode); this.OnKeyUpEvent(this, e); } } return(KeyBordHook.CallNextHookEx(KeyBordHook.hKeyboardHook, nCode, wParam, lParam)); }
public void Stop() { bool flag = true; if (KeyBordHook.hKeyboardHook != 0) { flag = KeyBordHook.UnhookWindowsHookEx(KeyBordHook.hKeyboardHook); KeyBordHook.hKeyboardHook = 0; } if (!flag) { throw new Exception("UnhookWindowsHookEx failed. "); } }
public void Start() { if (KeyBordHook.hKeyboardHook == 0) { this.KeyboardHookProcedure = new KeyBordHook.HookProc(this.KeyboardHookProc); Process currentProcess = Process.GetCurrentProcess(); ProcessModule mainModule = currentProcess.MainModule; KeyBordHook.hKeyboardHook = KeyBordHook.SetWindowsHookEx(13, this.KeyboardHookProcedure, KeyBordHook.GetModuleHandle(mainModule.ModuleName), 0); if (KeyBordHook.hKeyboardHook == 0) { this.Stop(); } } }