audiophonic
audiophonic

Reputation: 171

Detect pressed key on form

I want to detect pressed key on my form. Let's say I want to show message when F1 key is pressed.

I added code to KeyUp event related with Form1

private void Form1_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.F1)
    {
        MessageBox.Show("Key Pressed ");
    }
}

The thing is, that pressing F1 does not do anything. Not at all. Does anybody have any idea why does that not work?

Solution

I had to change Form1 KeyPreview properties to "true" and delete this.Controls.Add(this.webControl1); from InitializeComponent() in Form1.Designer.cs

Does anybody know how to solve my problem without deleting row from InitializeComponent()?

Upvotes: 0

Views: 245

Answers (3)

Rahul
Rahul

Reputation: 77926

If you want to handle the key press event irrespective of the control that currently has the focus then you should consider override the Control.ProcessCmdKey() method.

Here is a example: How do I capture Keys.F1 regardless of the focused control on a form?

Upvotes: 2

René Vogt
René Vogt

Reputation: 43936

You surely don't have a blank form but a form that contains some controls like textboxes etc...

If you press a key, this event is raised for the control that currently has the focus. So the for example the KeyUp event for your TextBox is raised, but not for your form.

To ensure the event is raised in your Form before it is raised for the focused control, set the KeyPreview property of your Form to true:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponents();
        this.KeyPreview = true;
    }
    ...

Or as Sadiq showed, set it in the UI designer.

Upvotes: 1

Sadique
Sadique

Reputation: 22841

Make sure your form has the KeyPreview property set to true.

Form.KeyPreview Property

Gets or sets a value indicating whether the form will receive key events before the event is passed to the control that has focus.

enter image description here

Upvotes: 1

Related Questions