/// <summary> /// Private hook that checks the return code /// and calls the overridden hook process <paramref name="hookProc"/> /// </summary> /// <param name="code">A code the hook procedure uses to determine /// how to process the message.</param> /// <param name="wParam">The virtual-key code of the key that generated /// the keystroke message.</param> /// <param name="lParam">The repeat count, scan code, extended-key flag, /// context code, previous key-state flag,</param> /// <see cref="https://msdn.microsoft.com/en-us/library/windows/desktop/ms644984%28v=vs.85%29.aspx"/> /// <returns></returns> private int _hookProc(int code, int wParam, ref KeyboardHookData lParam) { if (code >= 0) { //Pass on for other objects to process. /*return*/ this.hookProc(code, wParam, ref lParam); } //else return(CallNextHookEx(hhook, code, wParam, ref lParam)); }
/// <summary> /// Overridable function called by the hooked procedure /// function <typeparamref name="_hookProc"/>. /// </summary> /// <param name="code">A code the hook procedure uses to determine /// how to process the message.</param> /// <param name="wParam">The virtual-key code of the key that generated /// the keystroke message.</param> /// <param name="lParam">The repeat count, scan code, extended-key flag, /// context code, previous key-state flag,</param> /// <see cref="https://msdn.microsoft.com/en-us/library/windows/desktop/ms644984%28v=vs.85%29.aspx"/> /// <returns></returns> public virtual int hookProc( int code, int wParam, ref KeyboardHookData lParam) { Keys k = (Keys)lParam.vkCode; //Check for shift(s), alt, and ctrl. //Shift if (k == Keys.LShiftKey) { bLeftShiftHeld = bShiftHeld = (wParam == WM_KEYDOWN); } else if (k == Keys.RShiftKey) { bRightShiftHeld = bShiftHeld = (wParam == WM_KEYDOWN); } //Control if ((lParam.vkCode & 0xA2) == 0xA2 || (lParam.vkCode & 0xA3) == 0xA3) { bCtrlHeld = (wParam == WM_KEYDOWN); return(1); } //Alt if ((lParam.vkCode & 0xA4) == 0xA4 || (lParam.vkCode & 0xA5) == 0xA5) { bAltHeld = (wParam == WM_KEYDOWN); return(1); } //Win if (lParam.vkCode == 0x5B) { bWinHeld = (wParam == WM_KEYDOWN); return(1); } //Key Press Event KeyEventArgs kea = new KeyEventArgs(k); if ((wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) && (KeyDown != null)) { KeyDown(wParam, lParam); } else if ((wParam == WM_KEYUP || wParam == WM_SYSKEYUP) && (KeyUp != null)) { KeyUp(wParam, lParam); } if (kea.Handled) { return(1); } return(CallNextHookEx(hhook, code, wParam, ref lParam)); }
static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref KeyboardHookData lParam);