다음을 통해 공유


ASP.NET Windows Forms Application: Multiple key combination event (C#)

This is for a simple but effective way to capture events for multiple key strokes in C# say Alt + A, Ctrl + Q etc etc. This is a nice solution for a win form application.

  1. Set the property "KeyPreview" of the Form to true from the property list (press F4 or right click, go to Property).

  2. Create KeyPress event of the form, and overwrite KeyDown event there. As shown below, overwrite the KeyDown event with KeyDown event:
    private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    **{
                this.KeyDown += new KeyEventHandler(this.Form1_KeyDown);
    }
    **

  3. Then create KeyDown event of the form and handle the events from the key as shown below:
    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
               if (e.Alt && e.KeyCode == Keys.T) // for combination of Alt + T
                {
                    MessageBox.Show("Alt + T");
                }
                if (e.Control && e.KeyCode == Keys.Q) // for combination of Ctrl + Q
                {
                    MessageBox.Show("Ctrl + Q");
                }
                if (e.Shift && e.KeyCode == Keys.D) // for combination of Shift + D
                {
                    MessageBox.Show("Shift + D");
                }
                if (e.Alt && e.KeyCode == (Keys.RButton|Keys.ShiftKey |Keys.ControlKey) ) // Alt + Shift
                {
                    MessageBox.Show("Shift + Alt");
                }
    }