The MSDN Documentation has a good example of what you need to do. Here are a few important parts:
- Start with a simple "Windows Forms" application. While there are many other types of applications, WinForms is the simplest to start with.
Wire up the KeyPress event. In the Form constructor, you need to tell it what to do when it gets a KeyPress event. If you change the name of your function
begin
in your question above toForm1_KeyPress
(to more-accurately describe what it does), the following code should work:this.KeyPress += new KeyPressEventHandler(Form1_KeyPress);
Use
KeyPressEventArgs
instead ofKeyEventArgs
. It may or may not make a huge difference, but it is good to use the most-specificEventArgs
when you can so you can use properties specific to it.Pay attention to
KeyPressEventArgs.Handled
. If you have KeyPress (or some other keyboard events) on other objects on your forms, such as buttons or text boxes, you need to say whether the event was handled there or whether it should bubble up to the parent (in your case, to the Form).
EDIT (Thanks @RBarryYoung):
- Set
this.KeyPreview = true
in the form constructor. In order for your form to receive keyboard events that happen on child controls (such as buttons and text boxes) as mentioned in the tip immediately above this one, you need to set this property totrue
to allow the form to get a first look at Keyboard events that happen on the child. (Note: of course, this tip and the previous one only apply if you want the form to see these events. Sometimes, you might want keyboard shortcuts to be trapped in the child control instead of being handled in the parent.)