keypress event!

HSN

Newcomer
Joined
May 2, 2004
Messages
23
Hello,

I need to handle some key press events in a C# windows application. I thought I can use this:

Code:
[size=2][/size][size=2][color=#0000ff]private[/color][/size][size=2] [/size][size=2][color=#0000ff]void[/color][/size][size=2] MainForm_KeyPress([/size][size=2][color=#0000ff]object[/color][/size][size=2] sender, System.Windows.Forms.KeyPressEventArgs e)

{

MessageBox.Show("Hello!");

}

[/size]

But it didn't work! It should output a hello whenever I press a key but it doesn't do anything!
Can anyone help me please?
 
If you are using C# you also need to make sure you are adding the event handler to the event - if you are doing this through the designer then it should do it for you. If not either in the Form_Load event or the constructor you would need to add the line
C#:
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.MainForm_KeyPress);
if you have done this from the designer (and it looks like it from the naming convention) you need to make sure the form is receiving the keypress events. If you have any controls on the form then the active control will recieve the keypress rather than the form itself, you need to set the KeyPreview property of the form to true and things should work.
 
Yes in fact my problem was that I wasn't set the KeyPreview property to true. Now it works fine. But, how can I determine which key was pressed? Because, according to the key I have to take the appropriate action.
 
Back
Top