Exemplo n.º 1
0
        private static int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
        {
            var keyBoardHookInfo = (KeyHookExternal.KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyHookExternal.KeyboardHookStruct));
            var handled          = false;

            if (wParam == KeyHookExternal.WM_KEYDOWN || wParam == KeyHookExternal.WM_SYSKEYDOWN || wParam == KeyHookExternal.WM_KEYUP || wParam == KeyHookExternal.WM_SYSKEYUP)
            {
                var keyType = wParam == KeyHookExternal.WM_SYSKEYDOWN || wParam == KeyHookExternal.WM_SYSKEYUP ? EKeyType.System : EKeyType.Common;
                var state   = wParam == KeyHookExternal.WM_KEYDOWN || wParam == KeyHookExternal.WM_SYSKEYDOWN ? EState.Down : EState.Up;
                var keyData = (Keys)keyBoardHookInfo.VirtualKeyCode;
                var e       = new KeyboardEventArgs(state, keyType, keyData);

                if (_exclusiveKeyboardHandlers.Any())
                {
                    foreach (var kvp in _exclusiveKeyboardHandlers)
                    {
                        if (kvp.Value != null)
                        {
                            kvp.Value.Invoke(e);
                            handled = nCode > 0 && e.Handled;
                        }
                    }
                }
                else
                {
                    foreach (var kvp in _keyPressHandlers)
                    {
                        if (kvp.Value != null)
                        {
                            kvp.Value.Invoke(e);
                        }
                    }
                }
            }

            if (handled)
            {
                return(-1);
            }

            return(KeyHookExternal.CallNextHookEx(_keyboardHookHandle, nCode, wParam, lParam));
        }
Exemplo n.º 2
0
        private static void InitializeMonitor()
        {
            if (_keyboardHookHandle == 0)
            {
                _keyboardHookDelegate = KeyboardHookProc;

                _keyboardHookHandle = KeyHookExternal.SetWindowsHookEx(
                    KeyHookExternal.WH_KEYBOARD_LL,
                    _keyboardHookDelegate,
                    KeyHookExternal.GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName), 0);

                //If SetWindowsHookEx fails.
                if (_keyboardHookHandle == 0)
                {
                    //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
                    int errorCode = Marshal.GetLastWin32Error();
                    //do cleanup

                    //Initializes and throws a new instance of the Win32Exception class with the specified error.
                    throw new Win32Exception(errorCode);
                }
            }
        }