/// <summary> /// 键盘钩子处理函数 /// </summary> /// <param name="nCode"></param> /// <param name="wParam"></param> /// <param name="lParam"></param> /// <returns></returns> /// <remarks>此版本的键盘事件处理不是很好,还有待修正.</remarks> private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam) { switch (flags) { case "2": return(1); case "1": break; } bool handled = false; //it was ok and someone listens to events if ((nCode >= 0) && (this.OnKeyDown != null || this.OnKeyUp != null || this.OnKeyPress != null)) { //read structure KeyboardHookStruct at lParam KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); //raise KeyDown if (this.OnKeyDown != null && (wParam == (int)WM_KEYBOARD.WM_KEYDOWN || wParam == (int)WM_KEYBOARD.WM_SYSKEYDOWN)) { Keys keyData = (Keys)MyKeyboardHookStruct.VKCode; KeyEventArgs e = new KeyEventArgs(keyData); this.OnKeyDown(this, e); handled = handled || e.Handled; } // raise KeyPress if (this.OnKeyPress != null && wParam == (int)WM_KEYBOARD.WM_KEYDOWN) { bool isDownShift, isDownCapslock; try { isDownShift = ((Win32API.GetKeyStates(VK_SHIFT) & 0x80) == 0x80 ? true : false); isDownCapslock = (Win32API.GetKeyStates(VK_CAPITAL) != 0 ? true : false); } catch { isDownCapslock = false; isDownShift = false; } byte[] keyState = new byte[256]; Win32API.GetKeyboardState(keyState); byte[] inBuffer = new byte[2]; if (Win32API.ToAscii(MyKeyboardHookStruct.VKCode, MyKeyboardHookStruct.ScanCode, keyState, inBuffer, MyKeyboardHookStruct.Flags) == 1) { char key = (char)inBuffer[0]; if ((isDownCapslock ^ isDownShift) && Char.IsLetter(key)) { key = Char.ToUpper(key); } KeyPressEventArgs e = new KeyPressEventArgs(key); this.OnKeyPress(this, e); handled = handled || e.Handled; } } // raise KeyUp if (this.OnKeyUp != null && (wParam == (int)WM_KEYBOARD.WM_KEYUP || wParam == (int)WM_KEYBOARD.WM_SYSKEYUP)) { Keys keyData = (Keys)MyKeyboardHookStruct.VKCode; KeyEventArgs e = new KeyEventArgs(keyData); this.OnKeyUp(this, e); handled = handled || e.Handled; } } //if event handled in application do not handoff to other listeners if (handled) { return(1); } else { return(Win32API.CallNextHookEx(this.m_pKeyboardHook, nCode, wParam, lParam)); } }
/// <summary> /// 钩子类 /// </summary> /// <remarks>本类仅仅简单实现了 WH_KEYBOARD_LL 以及 WH_MOUSE_LL </remarks> public MyHook() { Win32API.GetKeyboardState(this.m_KeyState); }