Click here to Skip to main content
15,884,629 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How to detect two key inputs at the same time in my windows forms app for example, Ctrl and Z??
Posted
Updated 26-May-15 4:08am
v2

You need to add an eventhandler-method to the KeyDown-event of the control(s) for which you want to recognize this. You can do this either through the Designer via Properties > Events or manually. Example here for a TextBox-Control:
C#
// if you want to add it "manually" then place this
// line in the constructor of the form:
SomeTextBox.KeyDown += SomeTextBox_KeyDown;

private void SomeTextBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Z && e.Modifiers == Keys.Control)
    {
        // do something here
    }
}

If you want to process this event for more than one control, you can add the same eventhandler-method to the events of many controls:
C#
SomeTextBox.KeyDown += SomeControl_KeyDown;
SomeOtherTextBox.KeyDown += SomeControl_KeyDown;
SomeOtherControl.KeyDown += SomeControl_KeyDown;

In that case, if you want to know from which control the event originated, you have to look at the argument sender which will be a reference to that control.

If you want to receive that event also for the Form itself you have to set its property KeyPreview to true.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 26-May-15 10:09am    
Sure, a 5.
—SA
Sascha Lefèvre 26-May-15 10:21am    
Thank you, Sergey.
Manuele Camilletti 26-May-15 11:26am    
Nice and clean solution
Sascha Lefèvre 26-May-15 11:51am    
Thank you, Manuele.
You can use control.modifierkeys[^] to check if <alt>, <ctlr> or <shift> are pressed when you get an input in GUI apps.
In console apps you can use ConsoleKeyInfo.ConsoleModifiers[^].
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900