Detect when two keys are pressed at the same time

10,983

Solution 1

You have to keep track of keydown/keyup events, and keep a list of all the keys that are currently "down". The keyboard handler can only trigger on individual keys, and it's up to your code to detect/keep track of which ones are down, and if those individual keydown events are close enough to each other to be counted as "together".

Solution 2

put a break point in your key down event and press your two keys together.
examine the KeyData of the KeyEventArgs. it will show you what you have to use to detect two keys pressed together. Use some dummy code like this:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    MessageBox.Show("KeyData is: " + e.KeyData.Tostring());
}

like I have done for shift and r pressed together

e.KeyData = R | Shift

Solution 3

As you can see, you can use a timer event with booleans to detect if two keys are pressed:

bool keyup = false;
bool keyleft = false;

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Up)
    {
        keyup = true;
    }
    else if (e.KeyCode == Keys.Left)
    {
        keyleft = true;
    }
}

private void Form1_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Up)
    {
        keyup = false;
    }
    else if (e.KeyCode == Keys.Left)
    {
        keyleft = false;
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    if (keyleft && keyup)
    {
        Console.Beep(234, 589);
    }
}
Share:
10,983
The Mask
Author by

The Mask

Updated on July 29, 2022

Comments

  • The Mask
    The Mask almost 2 years

    I have no idea how do this.

    I know only how do detect one key:

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.C)
        {
            MessageBox.Show("C key");
        }
    }
    
  • Guy Levy
    Guy Levy over 2 years
    in what way is your answer different to other answers and explicitly the accepted one? What does your answer contribute?
  • Diego Quiros
    Diego Quiros over 2 years
    the other answers require multiples steps and tracking multiple items. This solution requires a single step to detect when both keys are pressed at the same time. Less complex, more efficient.