0
votes

Wondering if you can detect something like whether 'A','C' and Backspace are pressed at the same time in Windows Forms. So far what I've seen is how to check for things like 'Ctrl'+ 'T' on stack exchange, which is specific to a 'control key' being pressed.

In general, I'm looking for a way to check whether any 3 keys on the keyboard were held down at the same time. This could be Ctrl+Alt+Del, or even W+A+S+D or Up+Home+Insert.

1
Use the KeyDown event and check if the other keys are pressed. Winforms is missing a method to make that easy, but that can easily be added. You cannot do anything with Ctrl+Alt+Del, it is special. If you want to do WASD then you'd always consider simply using the KeyDown and KeyUp events to set the direction variables for the game loop. - Hans Passant

1 Answers

1
votes

This will create a dictionary to handle it. It seems to be working well through basic testing.

Dictionary<Keys, bool> keysDict;
public Form1()
{
    InitializeComponent();
    keysDict = new Dictionary<Keys, bool>();
    this.KeyDown += Form1_KeyDown;
    this.KeyUp += Form1_KeyUp;
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
    if (keysDict.ContainsKey(e.KeyCode))
    {
        keysDict[e.KeyCode] = false;
    }
}

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (!keysDict.ContainsKey(e.KeyCode))
    {
        keysDict.Add(e.KeyCode, true);
    }
    else
    {
        keysDict[e.KeyCode] = true;
    }
    if (keysDict.ContainsKey(Keys.A) && keysDict[Keys.A] && keysDict.ContainsKey(Keys.W) && keysDict[Keys.W] && keysDict.ContainsKey(Keys.S) && keysDict[Keys.S] && keysDict.ContainsKey(Keys.D) && keysDict[Keys.D])
    {
        Console.WriteLine("WASD Pressed");
    }
}

Edit If you want to see what keys are in the dictionary, simply press them, and then add a breakpoint to check what it resolved to.

In your comment, you asked about TAB, ENTER, SHIFT, and something else I believe. So, for example, I pressed enter, ctrl, shift, alt, tab, then put in a breakpoint, and I got:

{[Return, False]}
{[ControlKey, False]}
{[ShiftKey, False]}
{[Menu, False]}
{[Tab, False]}

Don't worry about them being false - it's not removing them from the dictionary when you keyup, it just sets it false, so you maintain the actual keys it recorded. The above are all keyup because I didn't have a breakpoint until after I pressed them, so they are no longer pressed when I break.