Search code examples
c#keycodealtctrl

Disable Ctrl or Alt key without registry using c#


I got a question about KeyCode and disabling special keys. I know this question was asked a few times, but I didn't find an answer I can use and which works so I came here to ask :)

I'm writing a program which blocks every key or key combinations (like Alt+F4 etc.). The application is not for me, it's for customers which only be able to navigate in this program. This all works fine, but I can't disable Left CTRL, Right CTRL or Alt key. I got this code for try blocking these keys:

private void webBrowser1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.LControlKey)
            {
                MessageBox.Show("LCtrl", "Warnung", MessageBoxButtons.OK);
            }

            else if (e.KeyCode == Keys.RControlKey)
            {
                MessageBox.Show("RCtrl", "Warnung", MessageBoxButtons.OK);

            }

            else if (e.KeyCode == Keys.Alt)
            {
                MessageBox.Show("Alt", "Warnung", MessageBoxButtons.OK);
            }

            else if (e.KeyCode == Keys.Delete)
            {
                MessageBox.Show("Delete", "Warnung", MessageBoxButtons.OK);
            }
        }

I only use MessageBox.Show(); that I can see if it works. Delete key works fine, but the other one not. Is it possible to do this without editing the registry and for Win7? Does anyone know why or can give me a hint?

Cheers

EDIT: I block all other keys in this way: Blocking shortcut keys using c#


Solution

  • Disclaimer: I'm not highly experienced in user input classes, but here's my input.

    CTRL and ALT are examples of modifier keys. That is to say, they modify other (non-modifier) keys to create a key combination. Your UI is likely only able to pick up a complete key combination. For example:

    private void keyPressed(object sender, PreviewKeyDownEventArgs e)
    {
        e.KeyCode == Key.A; // True (pressed A)
        e.KeyCode == Key.Control; // False (no key pressed)
        e.Modifiers == Keys.Control; // True (user is pressing the modifier CTRL)
        e.KeyCode == Key.A && e.Modifiers == Keys.Control; (pressed key A with modifier CTRL)
    }
    

    As for disabling the key, you could just catch e.Modifiers:

    private void ignoreCtrl(object sender, PreviewKeyDownArgs e)
    {
        if (e.Modifiers != Keys.Control) { /* Pass to handler */ }
        else { /* Discard */ }
    }
    

    Again, I'm not experienced in your particular framework but this would be my guess. I used the following SO sources:

    How to use multiple modifier keys in C#

    Determine whether modifier key was pressed