2
votes

I'm trying to suppress task switch keys (such as winkey, alt+tab, alt+esc, ctrl+esc, etc.) by using a low-level keyboard hook.

I'm using the following LowLevelKeyboardProc callback:

IntPtr HookCallback(int nCode, IntPtr wParam, ref KBDLLHOOKSTRUCT lParam) 
{
    if (nCode >= 0)
    {
            bool suppress = false;

            // Suppress left and right windows keys.
            if (lParam.Key == VK_LWIN || lParam.Key == VK_RWIN) 
                suppress = true;

            // Suppress alt-tab.
            if (lParam.Key == VK_TAB && HasAltModifier(lParam.Flags)) 
                suppress = true;

            // Suppress alt-escape.
            if (lParam.Key == VK_ESCAPE && HasAltModifier(lParam.Flags)) 
                suppress = true;

            // Suppress ctrl-escape.
            /* How do I hook CTRL-ESCAPE ? */

            // Suppress keys by returning 1.
            if (suppress) 
                return new IntPtr(1);
    }
    return CallNextHookEx(HookID, nCode, wParam, ref lParam);
}

bool HasAltModifier(int flags)
{
    return (flags & 0x20) == 0x20;
}

However, I'm at a loss as to how to suppress the CTRL+ESC combination. Any suggestions? Thanks.

2

2 Answers

1
votes

This should do the trick:

bool ControlDown = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
if (lParam.Key == VK_ESCAPE && ControlDown)
    suppress = true;
0
votes

This is what I got to work, I also have added the Alt+F4 to prevent an app closure.

    private static bool lastWasCtrlKey = false;

    private static IntPtr captureKey(int nCode, IntPtr wp, IntPtr lp)
    {
        if (nCode >= 0)
        {
            KBDLLHOOKSTRUCT objKeyInfo = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lp, typeof(KBDLLHOOKSTRUCT));

            // Disabling Windows keys 
            switch (objKeyInfo.key)
            {
                case Keys.RWin:
                case Keys.LWin:
                case Keys.Tab when HasAltModifier(objKeyInfo.flags):
                case Keys.Escape when HasAltModifier(objKeyInfo.flags):
                case Keys.Delete when HasAltModifier(objKeyInfo.flags):
                case Keys.F4 when HasAltModifier(objKeyInfo.flags):
                case Keys.Escape when lastWasCtrlKey:
                    lastWasCtrlKey = false;
                    return (IntPtr)1; 
                case Keys.LControlKey:
                case Keys.RControlKey:
                    lastWasCtrlKey = true;
                    break;
                case Keys.LShiftKey:
                case Keys.RShiftKey:
                    // Do nothing as the Ctrl key could have been before this
                    break;
                default:
                    lastWasCtrlKey = false;
                    break;
            }
        }
        return CallNextHookEx(ptrHook, nCode, wp, lp);
    }