Sunday, December 5, 2010

Check Pressing of Multiple Keys Simultaneously

In the functions KeyDown() and KeyPress(), which are implemented by nearly every control, key events can be analyzed.
The argument e of the type KeyEventArgs provides the methods and properties needed for that, for example with e.KeyCode can be checked, which key is pressed.
If multiple keys are pressed (at the same time), for each key an event is triggered, which does not help when wanting to check for key combinations.
In this post I will describe, how to check these cases with they property KeyData and Flags. But, these methods only work when a combination of Alt and / or Shift and / or Ctrl and at most one other key is pressed.
First with KeyData:
In this property 4 bytes are saved, the lower 2 ones represent the pressed key, the upper 2 ones the pressed function keys (Alt, Shift, Ctrl). If multiple keys are pressed, the byte values are combined via Or.
Now when you press a function keys and one other key, a unique bit combination is created. But of course, if multiple "normal" keys are pressed, this uniqueness is not guaranteed anymore, since the bits then can overlap.
To check a pressed combination, the value from e.KeyData is compared to an Or conjunction of the desired value.
The following sample terminates the program, if the key combination Ctrl + Shift + Alt + "E" is pressed:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyData == (Keys.Shift | Keys.Alt | Keys.Control | Keys.E))
        this.Close();
}

The same result though can also be used if checking the pressed key with e.KeyCode and then checking the properties e.Shift, e.Alt and e.Control (these properties are so called flags, representing the function keys), which describe whether these keys are pressed:

if (e.KeyCode == Keys.E && e.Shift && e.Alt && e.Control)
    this.Close();

No comments:

Post a Comment