Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire Form KeyPress event

I have a C# winform, on which I have 1 button.
Now, when I run my application, the button gets focus automatically.

The problem is KeyPress event of my form does not work because the button is focused.

I have tried this.Focus(); on FormLoad() event, but still the KeyPress event is not working.

like image 549
Javed Akram Avatar asked Mar 31 '11 11:03

Javed Akram


People also ask

What is the KeyPress event?

The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys.

What is difference between KeyPress and KeyDown event C#?

KeyDown is raised as soon as the user presses a key on the keyboard, while they're still holding it down. KeyPress is raised for character keys (unlike KeyDown and KeyUp, which are also raised for noncharacter keys) while the key is pressed.

What is KeyPress event in C#?

Key Press EventThis event fires or executes whenever a user presses a key in the TextBox. You should understand some important points before we are entering into the actual example. e. Keychar is a property that stores the character pressed from the Keyboard.

What is KeyPress event in VB NET?

The KeyPress event is used in the Windows Form when a user presses a character, space, or backspace key during the focus on the control, the KeyPress event occurs.


2 Answers

You need to override the ProcessCmdKey method for your form. That's the only way you're going to be notified of key events that occur when child controls have the keyboard focus.

Sample code:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    // look for the expected key
    if (keyData == Keys.A)
    {
        // take some action
        MessageBox.Show("The A key was pressed");

        // eat the message to prevent it from being passed on
        return true;

        // (alternatively, return FALSE to allow the key event to be passed on)
    }

    // call the base class to handle other key events
    return base.ProcessCmdKey(ref msg, keyData);
}

As for why this.Focus() doesn't work, it's because a form can't have the focus by itself. A particular control has to have the focus, so when you set focus to the form, it actually sets the focus to the first control that can accept the focus that has the lowest TabIndex value. In this case, that's your button.

like image 73
Cody Gray Avatar answered Nov 07 '22 05:11

Cody Gray


Try setting the Form's KeyPreview property to True.

like image 29
John Koerner Avatar answered Nov 07 '22 05:11

John Koerner