I used KeyDown event and some simple code like if (e.KeyCode == Keys.F1)
to capture F1 is pressed on a form BUT if there are some text boxes on the form or if there are some spreadsheets with Dock Fill on the form then the code above gets useless and does nothing. But I want to do something when user presses F1 on this form. so how do we capture a specific keydown event like F1 on the whole form..and I do not want to go to the route that capture the KeyDown of all other controls on the form and pass them to the Form for processing. is there any cleaner way to do this?
C# – How to capture Keys.F1 regardless of the focused control on a form
ckeydownkeyeventnetwinforms
Related Topic
- C# – Centering controls within a form in .NET (Winforms)
- C# – How should the ViewModel close the form
- C# – How to update the GUI from another thread
- C# – How to get the application’s path in a .NET console application
- C# trying to capture the KeyDown event on a form
- C# – How to remedy “The breakpoint will not currently be hit. No symbols have been loaded for this document.” warning
- Scala: list.flatten: no implicit argument matching parameter type (Any) = > Iterable[Any] was found
Best Answer
Yes, indeed there is. The correct way for the form to handle key events regardless of the control that currently has the input focus is to override the
ProcessCmdKey
method of your form class:You return
true
to indicate that you handled the keystroke and don't want it to be passed on to other controls. If you do want it to be passed on to the event handlers for other controls, simply returnfalse
.And you're best off ignoring the
KeyPreview
property. That's an anachronism from the VB 6 days and not really the preferred way of doing this in the .NET world. Further reading: Disadvantage of setting Form.KeyPreview = true?