12

I attempt to catch F5 on System.Windows.Forms for that I wrote:

partial class MainForm { (...) this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.MainForm_KeyUp); (...) } public partial class MainForm : Form { (...) private void MainForm_KeyUp(object sender, KeyEventArgs e) { Log("MainForm_KeyUp"); if (e.KeyCode == Keys.F5) { RefreshStuff(); } } } 

But my event catching looks not working.

Do you know how to cactch EventKey on System.Windows.Forms ?

3
  • You can first try testing it by doing something like this.... throw new Exception(e.KeyCode.ToString()); .... Maybe that will give you a clue about what you keycode you should use. Also, make sure to use e.Handled = true; Commented Sep 4, 2013 at 2:53
  • @ismellike and Grant Winney, adding an exception or breakpoint is not doing something more. Even I didn't got something from my Log box. That confirms event is not caught at all. Commented Sep 4, 2013 at 3:14
  • @Grant Winney, "What is this.KeyUp += ... in?" this is autogenerated by Visual Studio when I link from my designer view KeyUp event to MainForm_KeyUp. So that is in InitializeComponent() called by constructor of MainForm. Commented Sep 4, 2013 at 3:17

1 Answer 1

16

The KeyPreview property of the Form must be set to true.

When this property is set to true, the form will receive all KeyPress, KeyDown, and KeyUp events. After the form's event handlers have completed processing the keystroke, the keystroke is then assigned to the control with focus.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.