private int KeyboardHookProc(int nCode, int wParam, IntPtr lParam) { if ((nCode >= 0) && (OnKeyDownEvent != null || OnKeyUpEvent != null || OnKeyPressEvent != null)) { Win32Api.KeyboardHookStruct KeyDataFromHook = (Win32Api.KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(Win32Api.KeyboardHookStruct)); Keys keyData = (Keys)KeyDataFromHook.vkCode; if ((OnKeyDownEvent != null || OnKeyPressEvent != null) && (wParam == Win32Api.WM_KEYDOWN || wParam == Win32Api.WM_SYSKEYDOWN)) { if (IsCtrlAltShiftKeys(keyData) && _preKeysList.IndexOf(keyData) == -1) { _preKeysList.Add(keyData); } } if (OnKeyDownEvent != null && (wParam == Win32Api.WM_KEYDOWN || wParam == Win32Api.WM_SYSKEYDOWN)) { KeyEventArgs e = new KeyEventArgs(GetDownKeys(keyData)); OnKeyDownEvent?.Invoke(this, e); } if (OnKeyPressEvent != null && wParam == Win32Api.WM_KEYDOWN) { byte[] keyState = new byte[256]; Win32Api.GetKeyboardState(keyState); byte[] inBuffer = new byte[2]; if (Win32Api.ToAscii(KeyDataFromHook.vkCode, KeyDataFromHook.scanCode, keyState, inBuffer, KeyDataFromHook.flags) == 1) { KeyPressEventArgs e = new KeyPressEventArgs((char)inBuffer[0]); OnKeyPressEvent(this, e); } } if ((OnKeyDownEvent != null || OnKeyPressEvent != null) && (wParam == Win32Api.WM_KEYUP || wParam == Win32Api.WM_SYSKEYUP)) { if (IsCtrlAltShiftKeys(keyData)) { for (int i = _preKeysList.Count - 1; i >= 0; i--) { if (_preKeysList[i] == keyData) { _preKeysList.RemoveAt(i); } } } } if (OnKeyUpEvent != null && (wParam == Win32Api.WM_KEYUP || wParam == Win32Api.WM_SYSKEYUP)) { KeyEventArgs e = new KeyEventArgs(GetDownKeys(keyData)); OnKeyUpEvent?.Invoke(this, e); } } return(Win32Api.CallNextHookEx(hHook, nCode, wParam, lParam)); }
public void UnHook() { Win32Api.UnhookWindowsHookEx(hHook); }