Loading ...

How to capture keypress in Windows Forms?

0 (0votes)

You can capture any keypress in your Windows Forms based applications using any of these three events:

1. KeyPress: you can capture the key pressed using KeyPressEventArgs.Keychar property

2. KeyDown:

3. KeyUp

Now in windows applications, the Key events occur in this order:

   1.  KeyDown
   2.  KeyPress
   3.  KeyUp

Note that the KeyPress event is not raised by non-character keys likethe Function keys (F1 etc), so to track them you will need to use the  KeyDown and KeyUp events.

Let me show you how to capture the  F5 key press in your windows forms and fire a custom method during that keypress. Since F5 is a non-character key, you will need to use either KeyDown or KeyUp event. In this example we will use KeyDown event. First create an event handler for the key down (wire the event manually or using the properties window):

this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.MainForm_KeyDown);

Next create a handler for the event:

private void MainForm_KeyDown(object sender, KeyEventArgs e)
            if (e.KeyCode == Keys.F5)
                // call the refresh method
                Refresh(); //you can call any method here


Before running this code, make sure that you have set the Form's KeyPreview property to true else the form will not register any of the keyboard events.

Sometimes we would want to fire some custom code on a key press (like fire some method when a user presses "2" key) but we would not want any of the forms controls to capture that event. For example if the user presses the "2" numeric key, and the focus is on a textbox on the form, we want that the textbox should not get filled with its text proeprty=2, but our key press method should fire. For this, we need to set the KeyPressEventArgs.Handled property in the form's KeyPress event-handling method to true.

Comments (no comments yet)

Top Posts