25

I have a C# form with 5 buttons. The users enters the information and depending on the press of a function key, a specific action is performed. F9-Execute Order, F6-Save, F3-LookUp.

I have added the foolowing code:

OnForm_Load

this.KeyUp += new System.Windows.Forms.KeyEventHandler(KeyEvent);

and

private void KeyEvent(object sender, KeyEventArgs e) //Keyup Event 
    {
        if (e.KeyCode == Keys.F9)
        {
            MessageBox.Show("Function F9"); 
        }
        if (e.KeyCode == Keys.F6)
        {
            MessageBox.Show("Function F6");
        }
        else
            MessageBox.Show("No Function");

    }

but nothing happens

Thanks

0

1 Answer 1

51

You need to set

KeyPreview=True

for your form. Otherwise key press is swallowed by the control that has focus.

Sign up to request clarification or add additional context in comments.

2 Comments

Also in the last Visual Studio C# standard you need to set method to PreviewKeyDown instead of KeyPress to get function key working.
Ch3shire, using VS2017 I'm still getting all events on KeyPress with KeyPreview=true. I see no events fired on OnKeyPreviewDown. The setting works fine though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.