private void ProcessKeyPress(int code, int wParam, KeyboardHookStruct lParam) { //Append new keystroke to our buffer string Boolean isTerminatingKey = lParam.vkCode == 13 || lParam.vkCode == 0x0D || lParam.vkCode == 10 || lParam.vkCode == 0x0A; if (isTerminatingKey == false) { keyChar = (char)lParam.vkCode; if (keyChar != char.MinValue) { this.codeHook += keyChar; } return; } //This will handle double cr+lf case if (this.codeHook.Length <= 2) return; //Make a copy of this string String tempCodeString = "" + this.codeHook; this.codeHook = ""; signalService.WriteEntry("Code: " + tempCodeString); // Plays the sound associated with the hook keyboard SystemSounds.Asterisk.Play(); //Handle data input from RFID reader or keyboard //Init instant object this.signals = new List<Signal>(); this.signal = new Signal(); this.signal.Code = tempCodeString; this.signals.Add(signal); signalService.WriteEntry(" this.signals.Add(signal);"); //RunAsync(HttpVerb.POST); }
private int HookProc(int code, int wParam, ref KeyboardHookStruct lParam) { if (code >= 0 && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)) { //Call process key press ProcessKeyPress(code, wParam, lParam); } return CallNextHookEx(hhook, code, wParam, ref lParam); }
private int HookProc(int code, int wParam, ref KeyboardHookStruct lParam) { signalService.WriteEntry("Call hook"); if (code >= 0 && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)) { //Call process key press ProcessKeyPress(code, wParam, lParam); } signalService.WriteEntry("Call next hook"); return CallNextHookEx(hhook, code, wParam, ref lParam); }
private void OnHookInvoked(object sender, HookEventArgs e) { if (e.WParam == 256 && KeyDown != null) { KeyboardHookStruct khs = new KeyboardHookStruct(e); KeyDown(sender, new KeyEventArgs((Keys)khs.virtualKey | Control.ModifierKeys)); } else if (e.WParam == 257 && KeyUp != null) { KeyboardHookStruct khs = new KeyboardHookStruct(e); KeyUp(sender, new KeyEventArgs((Keys)khs.virtualKey | Control.ModifierKeys)); } }
private void ProcessKeyPress(int code, int wParam, KeyboardHookStruct lParam) { //If meet vkCode is Enter Key or CR/LF then submit code to server //http://www.racoindustries.com/blog/post/How-to-Program-Enter-Carriage-Return-or-Other-Post-Amble-Data-to-Scanner.aspx //http://msdn.microsoft.com/en-us/library/dd375731(v=vs.85).aspx //Append new keystroke to our buffer string Boolean isTerminatingKey = lParam.vkCode == 13 || lParam.vkCode == 0x0D || lParam.vkCode == 10 || lParam.vkCode == 0x0A; if (isTerminatingKey == false) { keyChar = (char)lParam.vkCode; if (keyChar != char.MinValue) { this.codeHook += keyChar; } return; } //This will handle double cr+lf case if (this.codeHook.Length <= 2) return; //Make a copy of this string String tempCodeString = "" + this.codeHook; this.codeHook = ""; // Plays the sound associated with the hook keyboard SystemSounds.Asterisk.Play(); //Handle data input from RFID reader or keyboard //Init instant object if (this.signals == null || this.signal == null) return; this.signal.Code = tempCodeString; this.signals.Add(signal); //Post signal to service apiHelper.PostSignals(this.signals); this.Unhook(); this.Hook(); }
/// <summary> /// The callback for the keyboard hook /// </summary> /// <param name="code">The hook code, if it isn't >= 0, the function shouldn't do anyting</param> /// <param name="wParam">The event type</param> /// <param name="lParam">The keyhook event information</param> /// <returns></returns> public int HookProc(int code, int wParam, ref KeyboardHookStruct lParam) { if (code < 0) { return(CallNextHookEx(_hhook, code, wParam, ref lParam)); } var key = (Keys)lParam.VkCode; //if (HookedKeys.Contains(Key)) //{ var kea = new KeyEventArgs(key); if ((wParam == WmKeydown || wParam == WmSyskeydown) && (KeyDown != null)) { KeyDown(this, kea); } else if ((wParam == WmKeyup || wParam == WmSyskeyup)) { KeyUp?.Invoke(this, kea); } return(kea.Handled ? 1 : CallNextHookEx(_hhook, code, wParam, ref lParam)); //} }
private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr IParam) { if ((nCode >= 0) && (OnKeyDownEvent != null || OnKeyUpEvent != null || OnKeyPressEvent != null)) { KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(IParam, typeof(KeyboardHookStruct)); //引发OnKeyDownEvent if (OnKeyDownEvent != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)) { Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; KeyEventArgs e = new KeyEventArgs(keyData); OnKeyDownEvent(this, e); } //引发OnKeyUpEvent if (OnKeyUpEvent != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP)) { Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; //keyData.` KeyEventArgs e = new KeyEventArgs(keyData); OnKeyUpEvent(this, e); } //引发OnKeyPressEvent if (OnKeyPressEvent != null && (wParam == WM_KEYDOWN)) { byte[] keyState = new byte[256]; GetKeyboardState(keyState); byte[] inBuffer = new byte[2]; if (ToAscii(MyKeyboardHookStruct.vkCode, MyKeyboardHookStruct.scanCode, keyState, inBuffer, MyKeyboardHookStruct.flags) == 1) { //string anjian=inBuffer.ToString(); //System.Console.WriteLine(anjian); KeyPressEventArgs e = new KeyPressEventArgs((char)inBuffer[0]); OnKeyPressEvent(this, e); } } } return(CallNextHookEx(hKeyboardHook, nCode, wParam, IParam)); }
private const int WM_SYSKEYUP = 0x105; //SYSKEYUP private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam) { // 侦听键盘事件 if (nCode >= 0) { KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; // 键盘按下 if (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) { if (oldKey != keyData || oldwParam != wParam) { sw.Stop(); detailTextBox.Text += string.Format("Delay {0}\r\n", sw.ElapsedMilliseconds); detailTextBox.Text += string.Format("KeyPress {0}\r\n", keyData.ToString()); oldKey = keyData; oldwParam = wParam; sw.Restart(); } } // 键盘抬起 if (wParam == WM_KEYUP || wParam == WM_SYSKEYUP) { if (oldKey != keyData || oldwParam != wParam) { sw.Stop(); detailTextBox.Text += string.Format("Delay {0}\r\n", sw.ElapsedMilliseconds); detailTextBox.Text += string.Format("KeyUp {0}\r\n", keyData.ToString()); oldKey = keyData; oldwParam = wParam; sw.Restart(); } } } //如果返回1,则结束消息,这个消息到此为止,不再传递。 //如果返回0或调用CallNextHookEx函数则消息出了这个钩子继续往下传递,也就是传给消息真正的接受者 return(CallNextHookEx(hKeyboardHook, nCode, wParam, lParam)); }
//WM Keyboard Related Consts /// <summary> /// Keyboard Hook Listener Callback /// </summary> /// <param name="nCode"></param> /// <param name="wParam"></param> /// <param name="lParam"></param> /// <returns></returns> private IntPtr KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam) { if ((nCode >= 0) && (KeyDownEvent != null || KeyUpEvent != null || KeyPressEvent != null)) { KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); //Key Down if (KeyDownEvent != null && (wParam == NativeMethods.WM_KEYDOWN || wParam == NativeMethods.WM_SYSKEYDOWN)) { Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; KeyEventArgs e = new KeyEventArgs(keyData); KeyDownEvent(this, e); } //Key Press if (KeyPressEvent != null && wParam == NativeMethods.WM_KEYDOWN) { byte[] keyState = new byte[256]; NativeMethods.GetKeyboardState(keyState); byte[] inBuffer = new byte[2]; if (NativeMethods.ToAscii(MyKeyboardHookStruct.vkCode, MyKeyboardHookStruct.scanCode, keyState, inBuffer, MyKeyboardHookStruct.flags) == 1) { KeyPressEventArgs e = new KeyPressEventArgs((char)inBuffer[0]); KeyPressEvent(this, e); } } //Key up if (KeyUpEvent != null && (wParam == NativeMethods.WM_KEYUP || wParam == NativeMethods.WM_SYSKEYUP)) { Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; KeyEventArgs e = new KeyEventArgs(keyData); KeyUpEvent(this, e); } } //return true if you want to cancel the message. return(NativeMethods.CallNextHookEx(hKeyboardHook, nCode, (new IntPtr(wParam)), lParam)); }
private int KeyboardHookProc(int nCode, int wParam, IntPtr lParam) { // disable once SuggestUseVarKeywordEvident KeyboardHookStruct struct2 = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); // disable once SuggestUseVarKeywordEvident KeyEventArgs args = new KeyEventArgs((Keys)struct2.vkCode); Console.WriteLine(args.KeyValue.ToString()); if (this.code.Contains(args.KeyValue)) { return(1); } // if(args.KeyValue == 91 || // args.KeyValue == 92 || // args.KeyValue == 9 || // args.KeyValue == 27)//prevent which key code, $$$$$$$$ // { // return 1; // } return(CallNextHookEx(hKeyboardHook, nCode, wParam, lParam)); }
public void SetUp() { var kernel32 = MockRepository.GenerateStub<IKernel32>(); HookProc callback = delegate { return 1; }; _user32 = MockRepository.GenerateStub<IUser32>(); _user32.Stub(usr32 => usr32.SetWindowsHook(Arg<int>.Is.Anything, Arg<HookProc>.Is.Anything, Arg<IntPtr>.Is.Anything, Arg<int>.Is.Anything)) .WhenCalled(invocation=>callback = (HookProc)invocation.Arguments[1]) .Return(KEYBOARD_HOOK_HANDLE); EventHandler<KeyboardEventArgs> keyboardEventHandler = MockRepository.GenerateStub<EventHandler<KeyboardEventArgs>>(); KeyboardEventArgs eventArgs = new KeyboardEventArgs(0, new Dictionary<VirtualKeyCode, KeyState>()) {Handled = false}; keyboardEventHandler.Stub(handler => handler(null, null)).IgnoreArguments().WhenCalled(invocation => invocation.Arguments[1] = eventArgs); Keyboard keyboard = new Keyboard(_user32, kernel32); keyboard.KeyUp += keyboardEventHandler; KeyboardHookStruct keyboardData = new KeyboardHookStruct(); _ptr = Marshal.AllocHGlobal(Marshal.SizeOf(keyboardData)); Marshal.StructureToPtr(keyboardData, _ptr, true); callback(Constants.HC_ACTION, Constants.WM_KEYUP, _ptr); }
private int HookCallbackProcedure(int nCode, int wParam, IntPtr lParam) { KeyboardHookStruct keyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); if (wParam == 0x100 || wParam == 0x104) //KeyDown事件 { switch (keyboardHookStruct.vkCode) { case (int)Keys.F12: SaveDebugImage(); break; case (int)Keys.F11: Invoke(new Action(() => debugTextBox.AppendText($"{DateTime.Now.ToString("HH:mm:ss fff")}\r\n"))); break; case (int)Keys.F10: Start(); break; } } return(0); }
private const int WM_SYSKEYUP = 0x105; //SYSKEYUP private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam) { // 侦听键盘事件 if ((nCode >= 0) && (KeyDownEvent != null || KeyUpEvent != null || KeyPressEvent != null)) { KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); // raise KeyDown if (KeyDownEvent != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)) { Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; System.Windows.Forms.KeyEventArgs e = new System.Windows.Forms.KeyEventArgs(keyData); KeyDownEvent(this, e); } //键盘按下 if (KeyPressEvent != null && wParam == WM_KEYDOWN) { byte[] keyState = new byte[256]; GetKeyboardState(keyState); byte[] inBuffer = new byte[2]; if (ToAscii(MyKeyboardHookStruct.vkCode, MyKeyboardHookStruct.scanCode, keyState, inBuffer, MyKeyboardHookStruct.flags) == 1) { KeyPressEventArgs e = new KeyPressEventArgs((char)inBuffer[0]); KeyPressEvent(this, e); } } // 键盘抬起 if (KeyUpEvent != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP)) { Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; System.Windows.Forms.KeyEventArgs e = new System.Windows.Forms.KeyEventArgs(keyData); KeyUpEvent(this, e); } } //如果返回1,则结束消息,这个消息到此为止,不再传递。 //如果返回0或调用CallNextHookEx函数则消息出了这个钩子继续往下传递,也就是传给消息真正的接受者 return(CallNextHookEx(hKeyboardHook, nCode, wParam, lParam)); }
private int HookProc(int code, int wParam, ref KeyboardHookStruct lParam) { try { if (code < 0) { return(CallNextHookEx(hhook, code, wParam, ref lParam)); } var key = (Keys)lParam.vkCode; if (!catchAllKeyDowns && !hookedKeys.Contains(key)) { return(CallNextHookEx(hhook, code, wParam, ref lParam)); } var kea = new KeyEventArgs(key); if ((wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) && KeyDown != null) { KeyDown(this, kea); } else if (wParam == WM_KEYUP || wParam == WM_SYSKEYUP) { KeyUp?.Invoke(this, kea); } if (kea.Handled) { return(1); } return(CallNextHookEx(hhook, code, wParam, ref lParam)); } catch { return(0); } }
private const int WM_SYSKEYUP = 0x105; //SYSKEYUP private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam) { if ((nCode >= 0) && (KeyDownEvent != null || KeyUpEvent != null || KeyPressEvent != null)) { KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); // raise KeyDown if (KeyDownEvent != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)) { Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; KeyEventArgs e = new KeyEventArgs(keyData); KeyDownEvent(this, e); } if (KeyPressEvent != null && wParam == WM_KEYDOWN) { byte[] keyState = new byte[256]; GetKeyboardState(keyState); byte[] inBuffer = new byte[2]; if (ToAscii(MyKeyboardHookStruct.vkCode, MyKeyboardHookStruct.scanCode, keyState, inBuffer, MyKeyboardHookStruct.flags) == 1) { KeyPressEventArgs e = new KeyPressEventArgs((char)inBuffer[0]); KeyPressEvent(this, e); } } // ???? if (KeyUpEvent != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP)) { Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; KeyEventArgs e = new KeyEventArgs(keyData); KeyUpEvent(this, e); } } return(CallNextHookEx(hKeyboardHook, nCode, wParam, lParam)); }
private static int KeyboardHookProc(int nCode, IntPtr wParam, IntPtr lParam) { bool handled = false; if (nCode >= 0) { if ((int)wParam == WM_KEYDOWN || (int)wParam == WM_SYSKEYDOWN) { KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); Keys keyData = (Keys)MyKeyboardHookStruct.VirtualKeyCode; KeyEventArgs e = new KeyEventArgs(keyData); if (KeyboardHook.globalControlOnly) { e.Handled = true; } else { e.Handled = false; } _globalKeyDown.Invoke(null, e); handled = e.Handled; } } if (KeyboardHook.globalControlOnly) { return(-1); } return(CallNextHookEx(s_KeyboardHookHandle, nCode, wParam, lParam)); }
/// <summary> /// Called when a keyboard hook call had occured, use this instead of OnHookCall to read the keyboard structure. /// </summary> /// <param name="nCode"></param> /// <param name="wParam"></param> /// <param name="keyboardStruct"></param> /// <returns></returns> protected virtual IntPtr OnKeyboardHookCall(int nCode, IntPtr wParam, KeyboardHookStruct keyboardStruct) { // If events are being listened, call to the associated keyboard down or up and check if we should consume the event or not if (OnKeyboardEvent != null) { var consumeEvent = false; if ((int)wParam == Constants.WM_KEYDOWN || (int)wParam == Constants.WM_SYSKEYDOWN) { consumeEvent = OnKeyboardEvent(keyboardStruct.vkCode, KeyState.Keydown); } else if ((int)wParam == Constants.WM_KEYUP || (int)wParam == Constants.WM_SYSKEYUP) { consumeEvent = OnKeyboardEvent(keyboardStruct.vkCode, KeyState.Keyup); } if (consumeEvent) { return((IntPtr)Constants.CONSUME_INPUT); } } return(IntPtr.Zero); }
private IntPtr KeyboardHookProc(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode >= 0) { KeyboardHookStruct kbStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); if (wParam == (IntPtr)WM_KEYDOWN) { if (KeyDown != null) { KeyDown(null, new KeyEventArgs((Keys)kbStruct.VirtualKeyCode)); } } else if (wParam == (IntPtr)WM_KEYUP) { if (KeyUp != null) { KeyUp(null, new KeyEventArgs((Keys)kbStruct.VirtualKeyCode)); } } } return(CallNextHookEx(_hookHandle, nCode, wParam, lParam)); }
public int CaptureKeySinglePress(int code, int wParam, ref KeyboardHookStruct lParam) { if (code >= 0) { Key key = KeyInterop.KeyFromVirtualKey(lParam.VkCode); if (_clipboardEventsHandler.IsPastedBeforeDisplayClipboard()) { if (HandleEarlyPastedKeyPressed(key, wParam)) { return(1); } } if (TypeOfPressChecker.IsKeyDownPressed(wParam)) { KeyDownKeyHandle(key); } else if (TypeOfPressChecker.IsKeyUpPressed(wParam)) { KeyUpKeyHandle(key); } } return(CallNextHookEx(_hHook, code, wParam, ref lParam)); }
/// <summary> /// The callback for the keyboard hook /// </summary> /// <param name="code">The hook code, if it isn't >= 0, the function shouldn't do anyting</param> /// <param name="wParam">The event type</param> /// <param name="lParam">The keyhook event information</param> /// <returns></returns> int HookProc(int code, int wParam, ref KeyboardHookStruct lParam) { if (code >= 0) { Keys key = (Keys)lParam.vkCode; KeyEventArgs kea = new KeyEventArgs(key); if ((wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) && KeyDown != null) { if (KeyDown(kea)) { return(1); } } else if ((wParam == WM_KEYUP || wParam == WM_SYSKEYUP) && KeyUp != null) { if (KeyUp(kea)) { return(1); } } } return(CallNextHookEx(hhook, code, wParam, ref lParam)); }
internal static IEnumerable <KeyPressEventArgsExt> FromRawDataGlobal(CallbackData data) { var wParam = data.WParam; var lParam = data.LParam; if ((int)wParam != Messages.WM_KEYDOWN && (int)wParam != Messages.WM_SYSKEYDOWN) { yield break; } KeyboardHookStruct keyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); var virtualKeyCode = keyboardHookStruct.VirtualKeyCode; var scanCode = keyboardHookStruct.ScanCode; var fuState = keyboardHookStruct.Flags; if (virtualKeyCode == KeyboardNativeMethods.VK_PACKET) { var ch = (char)scanCode; yield return(new KeyPressEventArgsExt(ch, keyboardHookStruct.Time)); } else { char[] chars; KeyboardNativeMethods.TryGetCharFromKeyboardState(virtualKeyCode, scanCode, fuState, out chars); if (chars == null) { yield break; } foreach (var current in chars) { yield return(new KeyPressEventArgsExt(current, keyboardHookStruct.Time)); } } }
/// <summary> /// The callback for the keyboard hook /// </summary> /// <param name="code">The hook code, if it isn't >= 0, the function shouldn't do anyting</param> /// <param name="wParam">The event type</param> /// <param name="lParam">The keyhook event information</param> /// <returns></returns> public int HookProc(int code, int wParam, ref KeyboardHookStruct lParam) { if (code >= 0) { Keys key = (Keys)lParam.vkCode; if (HookedKeys.Contains(key)) { KeyEventArgs kea = new KeyEventArgs(key); 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(hhook, code, wParam, ref lParam)); }
/// <summary> /// 钩子之程的实现(keyboard) /// </summary> /// <param name="nCode"></param> /// <param name="wParam"></param> /// <param name="lParam"></param> /// <returns></returns> private IntPtr KeyboardHookCallback(int nCode, IntPtr wParam, ref KeyboardHookStruct lParam) { if (nCode >= 0) { if (userProcKeyboard != null) { bool flag = false; userProcKeyboard(lParam, out flag); if (flag) { return (System.IntPtr)1; //1没有意义。在这里为了返回。 } } } return CallNextHookEx(hookID, nCode, wParam, ref lParam); //调用下一个钩子,使得捕获的消息继续传送 }
internal static extern int CallNextHookEx(IntPtr id, int code, int wParam, ref KeyboardHookStruct lParam);
/// <summary> /// A callback function which will be called every time a keyboard activity detected. /// </summary> /// <param name="nCode"> /// [in] Specifies whether the hook procedure must process the message. /// If nCode is HC_ACTION, the hook procedure must process the message. /// If nCode is less than zero, the hook procedure must pass the message to the /// CallNextHookEx function without further processing and must return the /// value returned by CallNextHookEx. /// </param> /// <param name="wParam"> /// [in] Specifies whether the message was sent by the current thread. /// If the message was sent by the current thread, it is nonzero; otherwise, it is zero. /// </param> /// <param name="lParam"> /// [in] Pointer to a CWPSTRUCT structure that contains details about the message. /// </param> /// <returns> /// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx. /// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx /// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC /// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook /// procedure does not call CallNextHookEx, the return value should be zero. /// </returns> /// private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam) { //indicates if any of underlaing events set e.Handled flag bool handled = false; //Console.WriteLine(calledArtificially + "==" + wParam + "==" + lParam); //it was ok and someone listens to events if ((nCode >= 0) && (KeyDown != null || KeyUp != null || KeyPress != null)) { //read structure KeyboardHookStruct at lParam KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); //raise KeyDown if (KeyDown != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)) { Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; KeyEventArgs e = new KeyEventArgs(keyData); KeyDown(this, e); handled = handled || e.Handled; } // raise KeyPress if (KeyPress != null && wParam == WM_KEYDOWN) { bool isDownShift = ((GetKeyState(VK_SHIFT) & 0x80) == 0x80 ? true : false); bool isDownCapslock = (GetKeyState(VK_CAPITAL) != 0 ? true : false); byte[] keyState = new byte[256]; GetKeyboardState(keyState); byte[] inBuffer = new byte[2]; if (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); bool NumLock = ((GetKeyState(VK_NUMLOCK)) == 1 ? true : false); if (NumLock) { int num = FindNumber(numbers, e.KeyChar); if (num < 0) { num = FindNumber(capNumbers, e.KeyChar); } if (num < 0) { num = FindNumber(characters, fnCharacters, e.KeyChar); } if (num >= 0) { switch (num) { case 0: PressKeyboardButton(Keys.D0, e); break; case 1: PressKeyboardButton(Keys.D1, e); break; case 2: PressKeyboardButton(Keys.D2, e); break; case 3: PressKeyboardButton(Keys.D3, e); break; case 4: PressKeyboardButton(Keys.D4, e); break; case 5: PressKeyboardButton(Keys.D5, e); break; case 6: PressKeyboardButton(Keys.D6, e); break; case 47: // '/' if (!calledArtificially) { PressKeyboardButton(Keys.Divide, e); } break; case 42: // '*' PressKeyboardButton(Keys.Multiply, e); break; case 45: // '-' PressKeyboardButton(Keys.Subtract, e); break; case 43: // '+' if (!calledArtificially) { PressKeyboardButton(Keys.Add, e); } break; } if (!calledArtificially) { return(1); } } } KeyPress(this, e); handled = handled || e.Handled; } } // raise KeyUp if (KeyUp != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP)) { Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; KeyEventArgs e = new KeyEventArgs(keyData); KeyUp(this, e); handled = handled || e.Handled; } } //if event handled in application do not handoff to other listeners if (handled) { return(1); } else { return(CallNextHookEx(hKeyboardHook, nCode, wParam, lParam)); } }
void OnHookInvoked(object sender, HookEventArgs e) { if ((e.WParam == WM_KEYDOWN || e.WParam == WM_SYSKEYDOWN) && KeyDown != null) { KeyboardHookStruct khs = new KeyboardHookStruct(e); KeyEventArgsEx kea = new KeyEventArgsEx(khs.virtualKey, Control.ModifierKeys, khs.scanCode); KeyDown(sender, kea); e.Handled = kea.Handled; } else if ((e.WParam == WM_KEYUP || e.WParam == WM_SYSKEYUP) && KeyUp != null) { KeyboardHookStruct khs = new KeyboardHookStruct(e); KeyEventArgsEx kea = new KeyEventArgsEx(khs.virtualKey, Control.ModifierKeys, khs.scanCode); KeyUp(sender, kea); e.Handled = kea.Handled; } }
protected override int HookCallbackProcedure(int nCode, int wParam, IntPtr lParam) { bool handled = false; if (nCode > -1 && (KeyDown != null || KeyUp != null || KeyPress != null)) { KeyboardHookStruct keyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); // Is Control being held down? bool control = ((GetKeyState(VK_LCONTROL) & 0x80) != 0) || ((GetKeyState(VK_RCONTROL) & 0x80) != 0); // Is Shift being held down? bool shift = ((GetKeyState(VK_LSHIFT) & 0x80) != 0) || ((GetKeyState(VK_RSHIFT) & 0x80) != 0); // Is Alt being held down? bool alt = ((GetKeyState(VK_LALT) & 0x80) != 0) || ((GetKeyState(VK_RALT) & 0x80) != 0); // Is CapsLock on? bool capslock = (GetKeyState(VK_CAPITAL) != 0); // Create event using keycode and control/shift/alt values found above KeyEventArgs e = new KeyEventArgs( (Keys)( keyboardHookStruct.vkCode | (control ? (int)Keys.Control : 0) | (shift ? (int)Keys.Shift : 0) | (alt ? (int)Keys.Alt : 0) )); // Handle KeyDown and KeyUp events switch (wParam) { case WM_KEYDOWN: case WM_SYSKEYDOWN: if (KeyDown != null) { KeyDown(this, e); handled = handled || e.Handled; } break; case WM_KEYUP: case WM_SYSKEYUP: if (KeyUp != null) { KeyUp(this, e); handled = handled || e.Handled; } break; } // Handle KeyPress event if (wParam == WM_KEYDOWN && !handled && !e.SuppressKeyPress && KeyPress != null) { byte[] keyState = new byte[256]; byte[] inBuffer = new byte[2]; GetKeyboardState(keyState); if (ToAscii(keyboardHookStruct.vkCode, keyboardHookStruct.scanCode, keyState, inBuffer, keyboardHookStruct.flags) == 1) { char key = (char)inBuffer[0]; if ((capslock ^ shift) && Char.IsLetter(key)) { key = Char.ToUpper(key); } KeyPressEventArgs e2 = new KeyPressEventArgs(key); KeyPress(this, e2); handled = handled || e.Handled; } } } if (handled) { return(1); } else { return(CallNextHookEx(_handleToHook, nCode, wParam, lParam)); } }
// Hook loop private int HookProc(int code, int wParam, ref KeyboardHookStruct lParam) { try { if (code >= 0 && IsApplicationActivated()) { Keys key = (Keys)lParam.vkCode; KeyEventArgs kea = new KeyEventArgs(key); Debug.Print(wParam.ToString()); if (wParam == 256) // If a key is down { switch (key) { case Keys.Left: case Keys.A: Console.WriteLine(DateTime.Now.ToString("[yyyy-MM-dd - hh:mm:ss] ") + "Direction: left"); if (!directionSet) { if (graphicsEngineClass.SnakeHolderPublic.Count == 1) { CurrentDirectionPublic = SnakeDirection.Left; } else if (graphicsEngineClass.SnakeHolderPublic.Count > 1 && CurrentDirectionPublic != SnakeDirection.Right) { CurrentDirectionPublic = SnakeDirection.Left; } directionSet = true; } break; case Keys.Right: case Keys.D: Console.WriteLine(DateTime.Now.ToString("[yyyy-MM-dd - hh:mm:ss] ") + "Direction: right"); if (!directionSet) { if (graphicsEngineClass.SnakeHolderPublic.Count == 1) { CurrentDirectionPublic = SnakeDirection.Right; } else if (graphicsEngineClass.SnakeHolderPublic.Count > 1 && CurrentDirectionPublic != SnakeDirection.Left) { CurrentDirectionPublic = SnakeDirection.Right; } directionSet = true; } break; case Keys.Up: case Keys.W: Console.WriteLine(DateTime.Now.ToString("[yyyy-MM-dd - hh:mm:ss] ") + "Direction: up"); if (!directionSet) { if (graphicsEngineClass.SnakeHolderPublic.Count == 1) { CurrentDirectionPublic = SnakeDirection.Up; } else if (graphicsEngineClass.SnakeHolderPublic.Count > 1 && CurrentDirectionPublic != SnakeDirection.Down) { CurrentDirectionPublic = SnakeDirection.Up; } directionSet = true; } break; case Keys.Down: case Keys.S: Console.WriteLine(DateTime.Now.ToString("[yyyy-MM-dd - hh:mm:ss] ") + "Direction: down"); if (!directionSet) { if (graphicsEngineClass.SnakeHolderPublic.Count == 1) { CurrentDirectionPublic = SnakeDirection.Down; } else if (graphicsEngineClass.SnakeHolderPublic.Count > 1 && CurrentDirectionPublic != SnakeDirection.Up) { CurrentDirectionPublic = SnakeDirection.Down; } directionSet = true; } break; case Keys.Q: Console.WriteLine(DateTime.Now.ToString("[yyyy-MM-dd - hh:mm:ss] ") + "Restarting game"); graphicsEngineClass.DefaultGameState(); break; case Keys.J: if (mainClass.MainGameLoop.Enabled) { mainClass.MainGameLoop.Stop(); } break; case Keys.Escape: //if (!GameLoopTimer.Enabled && !GameOverMenu.Enabled) //{ // Settings.Left = (this.ClientSize.Width - Settings.Width) / 2; // Settings.Top = (this.ClientSize.Height - Settings.Height) / 2; // GameSpeedSettings.Focus(); // if (Settings.Enabled && Settings.Visible) // { // Settings.Enabled = false; // Settings.Visible = false; // } // else // { // Settings.Enabled = true; // Settings.Visible = true; // } //} //break; //case Keys.J: // if (GameOverMenu.Enabled && GameOverMenu.Visible) // { // RestartGame(); // GameOverMenu.Enabled = false; // GameOverMenu.Visible = false; // } // break; //case Keys.N: // if (GameOverMenu.Enabled && GameOverMenu.Visible) // { // GameOverMenu.Enabled = false; // GameOverMenu.Visible = false; // } // break; default: break; } //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); } } else if (wParam == 257) // If a key is released { switch (key) { case Keys.Q: //if (!Main_Class.gameRunningPublic) { Main_Class.gameRunningPublic = true; } break; default: break; } } } return(CallNextHookEx(hhook, code, wParam, ref lParam)); } catch (Exception err) { // TODO: Log it return(0); } }
private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam) { // it was ok and someone listens to events if ((nCode >= 0) && (KeyPress != null)) //(KeyDown!=null )) //|| KeyUp!=null )) //|| KeyPress!=null)) { KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); // raise KeyDown /* * if ( KeyDown!=null && ( wParam ==WM_KEYDOWN || wParam==WM_SYSKEYDOWN )) * { * Keys keyData=(Keys)MyKeyboardHookStruct.vkCode; * * /* * switch (keyData) * { * case Keys.D0: * keyData = Keys.NumPad0; * break; * case Keys.D1: * keyData = Keys.NumPad1; * break; * case Keys.D2: * keyData = Keys.NumPad2; * break; * case Keys.D3: * keyData = Keys.NumPad3; * break; * case Keys.D4: * keyData = Keys.NumPad4; * break; * case Keys.D5: * keyData = Keys.NumPad5; * break; * case Keys.D6: * keyData = Keys.NumPad6; * break; * case Keys.D7: * keyData = Keys.NumPad7; * break; * case Keys.D8: * keyData = Keys.NumPad8; * break; * case Keys.D9: * keyData = Keys.NumPad9; * break; * } * * * * KeyEventArgs e = new KeyEventArgs(keyData); * * KeyDown(this, e); * } */ // raise KeyPress if (KeyPress != null && wParam == WM_KEYDOWN) { byte[] keyState = new byte[256]; GetKeyboardState(keyState); byte[] inBuffer = new byte[2]; int result = ToAscii(MyKeyboardHookStruct.vkCode, MyKeyboardHookStruct.scanCode, keyState, inBuffer, MyKeyboardHookStruct.flags); if (result == 1) { KeyPressEventArgs e = new KeyPressEventArgs((char)inBuffer[0]); KeyPress(this, e); } else { if (MyKeyboardHookStruct.vkCode == 46) { new ClearKey().Engage(0); } if (MyKeyboardHookStruct.vkCode == 33 || MyKeyboardHookStruct.vkCode == 38) { PosContext.Instance.CurrentPosDisplay.PageUp(); } if (MyKeyboardHookStruct.vkCode == 34 || MyKeyboardHookStruct.vkCode == 40) { PosContext.Instance.CurrentPosDisplay.PageDown(); } } } // raise KeyUp /* if ( KeyUp!=null && ( wParam ==WM_KEYUP || wParam==WM_SYSKEYUP )) * { * Keys keyData=(Keys)MyKeyboardHookStruct.vkCode; * KeyEventArgs e = new KeyEventArgs(keyData); * KeyUp(this, e); * } */ } return(CallNextHookEx(hKeyboardHook, nCode, wParam, lParam)); }
private static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref KeyboardHookStruct lParam);
///<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); break; 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)); } }
public void SetUp() { var kernel32 = MockRepository.GenerateStub<IKernel32>(); HookProc callback = delegate { return 1; }; IUser32 user32 = MockRepository.GenerateStub<IUser32>(); user32.Stub(usr32 => usr32.SetWindowsHook(Arg<int>.Is.Anything, Arg<HookProc>.Is.Anything, Arg<IntPtr>.Is.Anything, Arg<int>.Is.Anything)) .WhenCalled(invocation=>callback = (HookProc)invocation.Arguments[1]) .Return(1); _keyDownHandler = MockRepository.GenerateStub<EventHandler<KeyboardEventArgs>>(); Keyboard keyboard = new Keyboard(user32, kernel32); keyboard.KeyDown += _keyDownHandler; KeyboardHookStruct keyboardData = new KeyboardHookStruct(); IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(keyboardData)); Marshal.StructureToPtr(keyboardData, ptr, true); callback(Constants.HC_ACTION, Constants.WM_KEYDOWN, ptr); }
/// <summary> /// A callback function which will be called every Time a keyboard activity detected. /// </summary> /// <param name="nCode"> /// [in] Specifies whether the hook procedure must process the message. /// If nCode is HC_ACTION, the hook procedure must process the message. /// If nCode is less than zero, the hook procedure must pass the message to the /// CallNextHookEx function without further processing and must return the /// value returned by CallNextHookEx. /// </param> /// <param name="wParam"> /// [in] Specifies whether the message was sent by the current thread. /// If the message was sent by the current thread, it is nonzero; otherwise, it is zero. /// </param> /// <param name="lParam"> /// [in] Pointer to a CWPSTRUCT structure that contains details about the message. /// </param> /// <returns> /// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx. /// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx /// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC /// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook /// procedure does not call CallNextHookEx, the return value should be zero. /// </returns> private static int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam) { if (!HookManager.Enabled) { //forward to other application return(CallNextHookEx(s_KeyboardHookHandle, nCode, wParam, lParam)); } //indicates if any of underlaing events set e.Handled flag bool handled = false; if (nCode >= 0) { //read structure KeyboardHookStruct at lParam KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); //raise KeyDown if (s_KeyDown != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)) { Keys keyData = (Keys)MyKeyboardHookStruct.VirtualKeyCode; KeyEventArgs e = new KeyEventArgs(keyData); s_KeyDown.Invoke(null, e); handled = e.Handled; #if HAX if (keyData == Keys.LShiftKey || keyData == Keys.RShiftKey) { _is_shift = true; } if (keyData == Keys.CapsLock) { if (GetKeyState(VK_CAPITAL) != 0) { _is_caps = false; } else { _is_caps = true; } } #endif } // raise KeyPress if (s_KeyPress != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)) { Keys keyData = (Keys)MyKeyboardHookStruct.VirtualKeyCode; if (keyData == Keys.LMenu || keyData == Keys.RMenu || keyData == Keys.LControlKey || keyData == Keys.RControlKey || keyData == Keys.LShiftKey || keyData == Keys.RShiftKey || keyData == Keys.LWin || keyData == Keys.RWin || keyData == Keys.CapsLock || keyData == Keys.Space || keyData == Keys.Up || keyData == Keys.Down || keyData == Keys.Left || keyData == Keys.Right || keyData == Keys.Home || keyData == Keys.End || keyData == Keys.PageUp || keyData == Keys.PageDown) { char key_char = char.MinValue; if (keyData == Keys.Space || keyData == Keys.Up || keyData == Keys.Down || keyData == Keys.Left || keyData == Keys.Right || keyData == Keys.Home || keyData == Keys.End || keyData == Keys.PageUp || keyData == Keys.PageDown) { if (keyData == Keys.Space) { key_char = ' '; } KeyPressExEventArgs e = new KeyPressExEventArgs(key_char, keyData); s_KeyPress.Invoke(null, e); handled = handled || e.Handled; _it_was_a_dead_key = false; } } else { #if !HAX bool isDownShift = ((GetKeyState(VK_SHIFT) & 0x80) == 0x80 ? true : false); bool isDownCapslock = (GetKeyState(VK_CAPITAL) != 0 ? true : false); #else bool isDownShift = _is_shift; bool isDownCapslock = _is_caps; #endif //System.IO.StreamWriter writer1 = new System.IO.StreamWriter("key_dump.txt", true); //writer1.WriteLine("Key pressed: " + ((Keys)MyKeyboardHookStruct.VirtualKeyCode).ToString() + "; Scan code: " + MyKeyboardHookStruct.ScanCode.ToString() + "; s_KeyPress = " + s_KeyPress.ToString() + "; wParam = " + wParam.ToString()); //writer1.WriteLine("IsShift = " + _is_shift.ToString() + "; IsCaps = " + _is_caps.ToString()); //writer1.Close(); byte[] keyState = new byte[256]; GetKeyboardState(keyState); byte[] inBuffer = new byte[2]; System.Text.StringBuilder sbString = new System.Text.StringBuilder(); IntPtr HKL = GetKeyboardLayout(0); //if (ToAscii(MyKeyboardHookStruct.VirtualKeyCode, // 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); // s_KeyPress.Invoke(null, e); // handled = handled || e.Handled; //} if (!IsDeadKey((uint)MyKeyboardHookStruct.VirtualKeyCode)) { if (!_it_was_a_dead_key) { switch (ToUnicodeEx((uint)MyKeyboardHookStruct.VirtualKeyCode, (uint)MyKeyboardHookStruct.ScanCode, keyState, sbString, 5, (uint)MyKeyboardHookStruct.Flags, HKL)) { case 1: { char key_char = sbString.ToString()[0]; //System.IO.StreamWriter writer2 = new System.IO.StreamWriter("ToUnicode_dump.txt", true); //writer2.WriteLine("char: " + key_char.ToString()); //writer2.Close(); if ((isDownCapslock ^ isDownShift) && Char.IsLetter(key_char)) { key_char = Char.ToUpper(key_char); } else if (Char.IsUpper(key_char)) { key_char = Char.ToLower(key_char); } KeyPressExEventArgs e = new KeyPressExEventArgs(key_char, (Keys)MyKeyboardHookStruct.VirtualKeyCode); s_KeyPress.Invoke(null, e); handled = handled || e.Handled; _it_was_a_dead_key = false; } break; case 0: { Keys key = (Keys)MyKeyboardHookStruct.VirtualKeyCode; if (key != Keys.LControlKey && key != Keys.RControlKey && key != Keys.LShiftKey && key != Keys.RShiftKey && key != Keys.LMenu && key != Keys.RMenu && key != Keys.CapsLock) { char key_char = char.MinValue; KeyPressExEventArgs e = new KeyPressExEventArgs(key_char, (Keys)MyKeyboardHookStruct.VirtualKeyCode); s_KeyPress.Invoke(null, e); handled = handled || e.Handled; //System.IO.StreamWriter writer2 = new System.IO.StreamWriter("ToUnicode_dump.txt", true); //writer2.WriteLine("char: " + key.ToString()); //writer2.Close(); _it_was_a_dead_key = false; } } break; } } else { uint vkey = MapVirtualKey((uint)MyKeyboardHookStruct.VirtualKeyCode, 2); char key_char = char.MinValue; try { key_char = Convert.ToChar(vkey); } catch { } if (key_char != char.MinValue) { if (!(isDownCapslock ^ isDownShift) && Char.IsLetter(key_char)) { key_char = Char.ToLower(key_char); } KeyPressExEventArgs e = new KeyPressExEventArgs(key_char, (Keys)MyKeyboardHookStruct.VirtualKeyCode); s_KeyPress.Invoke(null, e); handled = handled || e.Handled; _it_was_a_dead_key = false; } } } else { _it_was_a_dead_key = true; _last_dead_key_code = MyKeyboardHookStruct.VirtualKeyCode; } } } // raise KeyUp if (s_KeyUp != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP)) { Keys keyData = (Keys)MyKeyboardHookStruct.VirtualKeyCode; KeyEventArgs e = new KeyEventArgs(keyData); s_KeyUp.Invoke(null, e); handled = handled || e.Handled; #if HAX if (keyData == Keys.LShiftKey || keyData == Keys.RShiftKey) { _is_shift = false; } #endif //bool isDownShift = ((GetKeyState(VK_SHIFT) & 0x80) == 0x80 ? true : false); //bool isDownCapslock = (GetKeyState(VK_CAPITAL) != 0 ? true : false); //byte[] keyState = new byte[256]; //GetKeyboardState(keyState); //byte[] inBuffer = new byte[2]; //System.Text.StringBuilder sbString = new System.Text.StringBuilder(); //IntPtr HKL = GetKeyboardLayout(0); //if (!IsDeadKey((uint)MyKeyboardHookStruct.VirtualKeyCode)) //{ // if (!_it_was_a_dead_key) // { // switch (ToUnicodeEx((uint)MyKeyboardHookStruct.VirtualKeyCode, // (uint)MyKeyboardHookStruct.ScanCode, // keyState, // sbString, // 5, // (uint)MyKeyboardHookStruct.Flags, // HKL)) // { // case 1: // { // char key_char = sbString.ToString()[0]; // if ((isDownCapslock ^ isDownShift) && Char.IsLetter(key_char)) // key_char = Char.ToUpper(key_char); // else if (Char.IsUpper(key_char)) // key_char = Char.ToLower(key_char); // KeyEventExArgs e = new KeyEventExArgs(keyData, key_char); // s_KeyUp.Invoke(null, e); // handled = handled || e.Handled; // _it_was_a_dead_key = false; // } // break; // case 0: // { // //if (key != Keys.LControlKey && key != Keys.RControlKey && // // key != Keys.LShiftKey && key != Keys.RShiftKey && // // key != Keys.LMenu && key != Keys.RMenu && // // key != Keys.CapsLock) // //{ // // char key_char = char.MinValue; // // KeyEventExArgs e = new KeyEventExArgs(keyData, key_char); // // s_KeyUp.Invoke(null, e); // // handled = handled || e.Handled; // // _it_was_a_dead_key = false; // //} // char key_char = char.MinValue; // KeyEventExArgs e = new KeyEventExArgs(keyData, key_char); // s_KeyUp.Invoke(null, e); // handled = handled || e.Handled; // _it_was_a_dead_key = false; // } // break; // } // } // else // { // uint vkey = MapVirtualKey((uint)MyKeyboardHookStruct.VirtualKeyCode, 2); // char key_char = char.MinValue; // try // { // key_char = Convert.ToChar(vkey); // } // catch // { // } // if (key_char != char.MinValue) // { // if (!(isDownCapslock ^ isDownShift) && Char.IsLetter(key_char)) key_char = Char.ToLower(key_char); // KeyEventExArgs e = new KeyEventExArgs(keyData, key_char); // s_KeyUp.Invoke(null, e); // handled = handled || e.Handled; // _it_was_a_dead_key = false; // } // } //} //else //{ // //System.IO.StreamWriter writer1 = new System.IO.StreamWriter("key_dump.txt", true); // //writer1.WriteLine("Key pressed: " + ((Keys)MyKeyboardHookStruct.VirtualKeyCode).ToString() + "; last key: " + ((Keys)_last_dead_key_code).ToString() + "; it was a dead key: " + _it_was_a_dead_key.ToString()); // //writer1.Close(); // //if (_it_was_a_dead_key && _last_dead_key_code == MyKeyboardHookStruct.VirtualKeyCode) // //{ // // uint vkey = MapVirtualKey((uint)MyKeyboardHookStruct.VirtualKeyCode, 2); // // char key = Convert.ToChar(vkey); // // if (!(isDownCapslock ^ isDownShift) && Char.IsLetter(key)) key = Char.ToLower(key); // // KeyPressExEventArgs e = new KeyPressExEventArgs(key, (Keys)MyKeyboardHookStruct.VirtualKeyCode); // // s_KeyPress.Invoke(null, e); // // handled = handled || e.Handled; // // System.IO.StreamWriter writer2 = new System.IO.StreamWriter("ToUnicode_dump.txt", true); // // writer2.WriteLine("char: " + key.ToString()); // // writer2.Close(); // // _it_was_a_dead_key = false; // //} // //else // //{ // _it_was_a_dead_key = true; // _last_dead_key_code = MyKeyboardHookStruct.VirtualKeyCode; // //} //} } } //if event handled in application do not handoff to other listeners if (handled) { return(-1); } //forward to other application return(CallNextHookEx(s_KeyboardHookHandle, nCode, wParam, lParam)); }
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, ref KeyboardHookStruct lParam);
public void SetUp() { HookProc callback = delegate { return 1; }; var kernel32 = MockRepository.GenerateStub<IKernel32>(); _user32 = MockRepository.GenerateStub<IUser32>(); _user32.Stub(usr32 => usr32.SetWindowsHook(Arg<int>.Is.Anything, Arg<HookProc>.Is.Anything, Arg<IntPtr>.Is.Anything, Arg<int>.Is.Anything)) .WhenCalled(invocation=>callback = (HookProc)invocation.Arguments[1]) .Return(KEYBOARD_HOOK_HANDLE); Keyboard keyboard = new Keyboard(_user32, kernel32); keyboard.KeyUp += delegate { }; KeyboardHookStruct keyboardData = new KeyboardHookStruct(); _ptr = Marshal.AllocHGlobal(Marshal.SizeOf(keyboardData)); Marshal.StructureToPtr(keyboardData, _ptr, true); callback(1, Constants.WM_KEYUP, _ptr); }
/// <summary> /// A callback function which will be called every Time a keyboard activity detected. /// </summary> /// <param name="nCode"> /// [in] Specifies whether the hook procedure must process the message. /// If nCode is HC_ACTION, the hook procedure must process the message. /// If nCode is less than zero, the hook procedure must pass the message to the /// CallNextHookEx function without further processing and must return the /// value returned by CallNextHookEx. /// </param> /// <param name="wParam"> /// [in] Specifies whether the message was sent by the current thread. /// If the message was sent by the current thread, it is nonzero; otherwise, it is zero. /// </param> /// <param name="lParam"> /// [in] Pointer to a CWPSTRUCT structure that contains details about the message. /// </param> /// <returns> /// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx. /// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx /// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC /// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook /// procedure does not call CallNextHookEx, the return value should be zero. /// </returns> private static int KeyboardHookProc(int nCode, IntPtr wParam, IntPtr lParam) { //indicates if any of underlaing events set e.Handled flag bool handled = false; if (nCode >= 0) { WM command = (WM)wParam; //read structure KeyboardHookStruct at lParam KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); //raise KeyDown if (s_KeyDown != null && (command == WM.WM_KEYDOWN || command == WM.WM_SYSKEYDOWN)) { Keys keyData = (Keys)MyKeyboardHookStruct.VirtualKeyCode; KeyEventArgs e = new KeyEventArgs(keyData); s_KeyDown.Invoke(null, e); handled = e.Handled; } // raise KeyPress if (s_KeyPress != null && command == WM.WM_KEYDOWN) { bool isDownShift = ((User32.GetKeyState((int)VK.VK_SHIFT) & 0x80) == 0x80 ? true : false); bool isDownCapslock = (User32.GetKeyState((int)VK.VK_CAPITAL) != 0 ? true : false); byte[] keyState = new byte[256]; User32.GetKeyboardState(keyState); byte[] inBuffer = new byte[2]; if (User32.ToAscii(MyKeyboardHookStruct.VirtualKeyCode, 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); s_KeyPress.Invoke(null, e); handled = handled || e.Handled; } } // raise KeyUp if (s_KeyUp != null && (command == WM.WM_KEYUP || command == WM.WM_SYSKEYUP)) { Keys keyData = (Keys)MyKeyboardHookStruct.VirtualKeyCode; KeyEventArgs e = new KeyEventArgs(keyData); s_KeyUp.Invoke(null, e); handled = handled || e.Handled; } } //if event handled in application do not handoff to other listeners if (handled) { return(-1); } //forward to other application return(User32.CallNextHookEx(s_KeyboardHookHandle, nCode, wParam, lParam)); }
/// <summary> /// The callback for the keyboard hook /// </summary> /// <param name="code">The hook code, if it isn't >= 0, the function shouldn't do anyting</param> /// <param name="wParam">The event type</param> /// <param name="lParam">The keyhook event information</param> /// <returns></returns> public static int hookProc(int code, int wParam, ref KeyboardHookStruct lParam) { if (code >= 0) { Keys key = (Keys)lParam.vkCode; if (HookedKeys.Contains(key)) { KeyEventArgs kea = new KeyEventArgs(key); if ((wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) && (KeyDown != null)) { KeyDown(null, kea); } else if ((wParam == WM_KEYUP || wParam == WM_SYSKEYUP) && (KeyUp != null)) { KeyUp(null, kea); } if (kea.Handled) { return 1; } } } return CallNextHookEx(hhook, code, wParam, ref lParam); }
public static extern int CallNextHookEx(IntPtr hHk, int nCode, WindowsMessage wParam, ref KeyboardHookStruct lParam);
private static IntPtr InternalHookDelegate(int code, int wParam, IntPtr lParam) { try { if (code >= 0 && wParam == 256) { KeyboardHookStruct khs = new KeyboardHookStruct(lParam); int keyCode = khs.virtualKey; AppCommands appCommand = KeyCodeToAppCommand((Keys) khs.virtualKey); if (appCommand == AppCommands.None) { if (khs.virtualKey == (int) Keys.LShiftKey || khs.virtualKey == (int) Keys.LControlKey || khs.virtualKey == (int) Keys.RShiftKey || khs.virtualKey == (int) Keys.RControlKey) return CallNextHookEx(_hookHandle, code, wParam, lParam); if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift) keyCode |= 0x00100000; if ((Control.ModifierKeys & Keys.Control) == Keys.Control) keyCode |= 0x01000000; if ((Control.ModifierKeys & Keys.Alt) == Keys.Alt) keyCode |= 0x10000000; } else { keyCode |= (((int) appCommand) << 8); } if (_registered) { byte[] bytes = IrssMessage.EncodeRemoteEventData("Keyboard", String.Format("{0:X8}", keyCode)); IrssMessage message = new IrssMessage(MessageType.ForwardRemoteEvent, MessageFlags.Notify, bytes); _client.Send(message); } if (_stealAppCommands && appCommand != AppCommands.None) return new IntPtr(1); } } catch (Exception ex) { IrssLog.Error(ex); } return CallNextHookEx(_hookHandle, code, wParam, lParam); }
/// <summary> 键盘钩子处理函数 /// </summary> private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam) { //为 2 ,直接返回,不响应键盘事件 if (flags == HookType.Keyboard || flags == HookType.All) { } else { return(Hocy_Hook.CallNextHookEx(this.m_pKeyboardHook, nCode, wParam, lParam)); } 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 = ((Hocy_Hook.GetKeyStates(VK_SHIFT) & 0x80) == 0x80 ? true : false); isDownCapslock = (Hocy_Hook.GetKeyStates(VK_CAPITAL) != 0 ? true : false); } catch { isDownCapslock = false; isDownShift = false; } byte[] keyState = new byte[256]; Hocy_Hook.GetKeyboardState(keyState); byte[] inBuffer = new byte[2]; if (Hocy_Hook.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; } } //handled 为true, 则其他程序无法接受到键盘事件 if (handled) { return(1); } else { return(Hocy_Hook.CallNextHookEx(this.m_pKeyboardHook, nCode, wParam, lParam)); } }
private static int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam) { bool handled = false; if (nCode >= 0) { KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); Keys keyData = (Keys)MyKeyboardHookStruct.VirtualKeyCode; KeyEventArgs e = new KeyEventArgs(keyData); //raise KeyDown if (wParam == Charakters.WM_KEYDOWN || wParam == Charakters.WM_SYSKEYDOWN) { _KeyPress?.Invoke(null, e); // tak czy siak keypress sie wykona bool czyOdpalicEvent = false; if (!kliknieteKlawisze.ContainsKey(e.KeyValue)) { kliknieteKlawisze.Add(e.KeyValue, true); czyOdpalicEvent = true; } else { if (kliknieteKlawisze[e.KeyValue] == false) { kliknieteKlawisze[e.KeyValue] = true; czyOdpalicEvent = true; } } if (czyOdpalicEvent) { if (_KeyDown != null) { _KeyDown.Invoke(null, e); handled = e.Handled; } } } // raise KeyUp if (wParam == Charakters.WM_KEYUP || wParam == Charakters.WM_SYSKEYUP) { bool czyOdpalicEvent = false; if (!kliknieteKlawisze.ContainsKey(e.KeyValue)) { kliknieteKlawisze.Add(e.KeyValue, false); czyOdpalicEvent = true; } else { if (kliknieteKlawisze[e.KeyValue] == true) { kliknieteKlawisze[e.KeyValue] = false; czyOdpalicEvent = true; } } if (czyOdpalicEvent) { if (_KeyUp != null) { _KeyUp.Invoke(null, e); handled = e.Handled; } } } } if (handled) { return(-1); } return(CallNextHookEx(HandleKeyboardHookID, nCode, wParam, lParam)); }
private int InternalHookDelegate(int code, int wParam, IntPtr lParam) { if (code >= 0 && wParam == 256) { KeyboardHookStruct khs = new KeyboardHookStruct(lParam); int keyCode = khs.virtualKey; AppCommands appCommand = KeyCodeToAppCommand((Keys) khs.virtualKey); if (appCommand == AppCommands.None) { if (khs.virtualKey == (int) Keys.LShiftKey || khs.virtualKey == (int) Keys.LControlKey || khs.virtualKey == (int) Keys.RShiftKey || khs.virtualKey == (int) Keys.RControlKey) return CallNextHookEx(_hookHandle, code, wParam, lParam); if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift) keyCode |= 0x00100000; if ((Control.ModifierKeys & Keys.Control) == Keys.Control) keyCode |= 0x01000000; if ((Control.ModifierKeys & Keys.Alt) == Keys.Alt) keyCode |= 0x10000000; } else { keyCode |= (((int) appCommand) << 8); } if (_remoteButtonHandler != null) _remoteButtonHandler(Name, String.Format("{0:X8}", keyCode)); if (_stealAppCommands && appCommand != AppCommands.None) return 1; } return CallNextHookEx(_hookHandle, code, wParam, lParam); }
/// <summary> /// 按键处理 /// </summary> /// <param name="nCode"></param> /// <param name="wParam"></param> /// <param name="lParam"></param> /// <returns>返回1,则结束消息。返回0或调用CallNextHookEx函数则消息出了这个钩子继续往下传递,传递给真正接受者</returns> private int KeyboardHookProc(int nCode, int wParam, IntPtr lParam) { // 按键处理,返回1,则结束消息。返回0或调用CallNextHookEx函数则消息出了这个钩子继续往下传递,传递给真正接受者 // 侦听键盘事件 if (nCode >= 0 && wParam == 0x0100) { KeyboardHookStruct keyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); // 开关 if (keyboardHookStruct.vkCode == 20 || keyboardHookStruct.vkCode == 160 || keyboardHookStruct.vkCode == 161) { _isLocked = !_isLocked; } if (_isLocked) { #region 翻页 if (keyboardHookStruct.vkCode == 33) { OnPaged(-1); // 上一页 } else if (keyboardHookStruct.vkCode == 34) { OnPaged(1); // 下一页 } #endregion if (_isStarted && keyboardHookStruct.vkCode >= 48 && keyboardHookStruct.vkCode <= 57) { var c = int.Parse(((char)keyboardHookStruct.vkCode).ToString()); OnSpaced(c); // 空格 _isStarted = false; return(1); } if (_isStarted && keyboardHookStruct.vkCode == 8) { OnBacked(); // 删除 return(1); } if ((keyboardHookStruct.vkCode >= 65 && keyboardHookStruct.vkCode <= 90 || keyboardHookStruct.vkCode == 32)) { if (keyboardHookStruct.vkCode >= 65 && keyboardHookStruct.vkCode <= 90) { Keys keyData = (Keys)keyboardHookStruct.vkCode; KeyEventArgs e = new KeyEventArgs(keyData); KeyUpEvent(this, e); // 按键 _isStarted = true; } else // 32 { OnSpaced(0); _isStarted = false; } return(1); } else { return(0); // 后续操作 } } } return(Win32Api.CallNextHookEx(hKeyboardHook, nCode, wParam, lParam)); }
/// <summary> /// 键盘钩子程序 /// </summary> /// <param name="nCode"></param> /// <param name="wParam"></param> /// <param name="lParam"></param> /// <returns></returns> private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam) { //Console.WriteLine("事件激发"); //Console.WriteLine(wParam); //Console.WriteLine(preKeys.ToArray().Length); if ((nCode >= 0) && (OnKeyDownEvent != null || OnKeyUpEvent != null || OnKeyPressEvent != null)) { //Console.WriteLine(1); KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); //当有OnKeyDownEvent 或 OnKeyPressEvent不为null时,ctrl alt shift keyup时 preKeys //中的对应的键增加 if ((OnKeyDownEvent != null || OnKeyPressEvent != null) && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)) { Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; //Console.WriteLine(keyData); if (IsCtrlAltShiftKeys(keyData) && preKeys.IndexOf(keyData) == -1) { preKeys.Add(keyData); } } //引发OnKeyDownEvent if (OnKeyDownEvent != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)) { Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; KeyEventArgs e = new KeyEventArgs(GetDownKeys(keyData)); OnKeyDownEvent(this, e); } //引发OnKeyPressEvent if (OnKeyPressEvent != null && wParam == WM_KEYDOWN) { byte[] keyState = new byte[256]; GetKeyboardState(keyState); byte[] inBuffer = new byte[2]; if (ToAscii(MyKeyboardHookStruct.vkCode, MyKeyboardHookStruct.scanCode, keyState, inBuffer, MyKeyboardHookStruct.flags) == 1) { KeyPressEventArgs e = new KeyPressEventArgs((char)inBuffer[0]); OnKeyPressEvent(this, e); } } //当有OnKeyDownEvent 或 OnKeyPressEvent不为null时,ctrl alt shift keyup时 preKeys //中的对应的键删除 if ((OnKeyDownEvent != null || OnKeyPressEvent != null) && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP)) { Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; if (IsCtrlAltShiftKeys(keyData)) { for (int i = preKeys.Count - 1; i >= 0; i--) { if (preKeys[i] == keyData) { preKeys.RemoveAt(i); } } } } //引发OnKeyUpEvent if (OnKeyUpEvent != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP)) { Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; KeyEventArgs e = new KeyEventArgs(GetDownKeys(keyData)); OnKeyUpEvent(this, e); } } return(CallNextHookEx(hKeyboardHook, nCode, wParam, lParam)); }
/// <summary> /// A callback function which will be called every time a keyboard activity detected. /// </summary> /// <param name="nCode"> /// [in] Specifies whether the hook procedure must process the message. /// If nCode is HC_ACTION, the hook procedure must process the message. /// If nCode is less than zero, the hook procedure must pass the message to the /// CallNextHookEx function without further processing and must return the /// value returned by CallNextHookEx. /// </param> /// <param name="wParam"> /// [in] Specifies whether the message was sent by the current thread. /// If the message was sent by the current thread, it is nonzero; otherwise, it is zero. /// </param> /// <param name="lParam"> /// [in] Pointer to a CWPSTRUCT structure that contains details about the message. /// </param> /// <returns> /// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx. /// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx /// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC /// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook /// procedure does not call CallNextHookEx, the return value should be zero. /// </returns> private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam) { //indicates if any of underlaing events set e.Handled flag bool handled = false; //it was ok and someone listens to events if ((nCode >= 0) && (KeyDown != null || KeyUp != null || KeyPress != null)) { //read structure KeyboardHookStruct at lParam KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct)); //raise KeyDown if (KeyDown != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)) { Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; KeyEventArgs e = new KeyEventArgs(keyData); KeyDown(this, e); handled = handled || e.Handled; } // raise KeyPress if (KeyPress != null && wParam == WM_KEYDOWN) { bool isDownShift = ((GetKeyState(VK_SHIFT) & 0x80) == 0x80 ? true : false); bool isDownCapslock = (GetKeyState(VK_CAPITAL) != 0 ? true : false); byte[] keyState = new byte[256]; GetKeyboardState(keyState); byte[] inBuffer = new byte[2]; if (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); KeyPress(this, e); handled = handled || e.Handled; } } // raise KeyUp if (KeyUp != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP)) { Keys keyData = (Keys)MyKeyboardHookStruct.vkCode; KeyEventArgs e = new KeyEventArgs(keyData); KeyUp(this, e); handled = handled || e.Handled; } } //if event handled in application do not handoff to other listeners if (handled) { return(1); } else { return(CallNextHookEx(hKeyboardHook, nCode, wParam, lParam)); } }
/// <summary> /// The callback for the keyboard hook /// </summary> /// <param name="code">The hook code, if it isn't >= 0, the function shouldn't do anyting</param> /// <param name="wParam">The event type</param> /// <param name="lParam">The keyhook event information</param> /// <returns></returns> private int HookProc(int code, int wParam, ref KeyboardHookStruct lParam) { bool doContinue = true; var ret = 1; if (this.OnKeyComboPressed != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)) { var key = (Keys)lParam.vkCode; var keyCombos = this.KeyCombos.Where(x => x.Key == key); if(keyCombos.Count() > 0) { KeyModifier modifier = KeyModifier.None; if (KeyState.IsControlDown) { modifier |= KeyModifier.Control; } if(KeyState.IsShiftDown) { modifier |= KeyModifier.Shift; } if (KeyState.IsWinDown) { modifier |= KeyModifier.Win; } if (KeyState.IsAltDown) { modifier |= KeyModifier.Alt; } doContinue = keyCombos.Where(x => x.Modifier == modifier) .All(x => { this.keyComboPressEventArgs.Continue = true; this.keyComboPressEventArgs.KeyCombo = x; this.OnKeyComboPressed(this, this.keyComboPressEventArgs); return this.keyComboPressEventArgs.Continue; }); } } if(doContinue) ret = CallNextHookEx(this._hhook, code, wParam, ref lParam); return ret; }