Beispiel #1
0
        private static int OnKey(int msg, NativeMethods.KBDLLHOOKSTRUCT key)
        {
            var result = 0;

            foreach (var notificationEntry in NotificationEntries)
            {
                // It error code is Null, have to ignore the exception
                // For some unknow raison, sometime GetFocuseWindows throw an exception
                // Mainly when the station is unlocked, or after an admin password is asked
                try
                {
                    if (GetFocusWindow() != notificationEntry.WindowHandle || notificationEntry.KeyCode != key.vkCode)
                    {
                        continue;
                    }
                    var modifierKeys = GetModifierKeyState();
                    if (!ModifierKeysMatch(notificationEntry.ModifierKeys, modifierKeys))
                    {
                        continue;
                    }

                    var wParam = new IntPtr(msg);
                    var lParam = new HookKeyMsgData
                    {
                        KeyCode      = key.vkCode,
                        ModifierKeys = modifierKeys,
                        WasBlocked   = notificationEntry.Block
                    };

                    if (!PostMessage(notificationEntry.WindowHandle, HookKeyMsg, wParam, lParam))
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }

                    if (notificationEntry.Block)
                    {
                        result = 1;
                    }
                }
                catch (Win32Exception e)
                {
                    if (e.NativeErrorCode != 0)
                    {
                        throw;
                    }
                }
            }

            return(result);
        }
Beispiel #2
0
        private static IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, NativeMethods.KBDLLHOOKSTRUCT lParam)
        {
            var wParamInt = wParam.ToInt32();
            var result    = 0;

            if (nCode != NativeMethods.HC_ACTION)
            {
                return(NativeMethods.CallNextHookEx(_hook, nCode, wParam, lParam));
            }
            // ReSharper disable once SwitchStatementMissingSomeCases
            switch (wParamInt)
            {
            case NativeMethods.WM_KEYDOWN:
            case NativeMethods.WM_SYSKEYDOWN:
            case NativeMethods.WM_KEYUP:
            case NativeMethods.WM_SYSKEYUP:
                result = OnKey(wParamInt, lParam);
                break;
            }

            return(result != 0 ? new IntPtr(result) : NativeMethods.CallNextHookEx(_hook, nCode, wParam, lParam));
        }