HSN Posted May 10, 2005 Posted May 10, 2005 Hello, I need to handle some key press events in a C# windows application. I thought I can use this: [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? Quote
Administrators PlausiblyDamp Posted May 10, 2005 Administrators Posted May 10, 2005 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 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. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
HSN Posted May 10, 2005 Author Posted May 10, 2005 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. Quote
Administrators PlausiblyDamp Posted May 10, 2005 Administrators Posted May 10, 2005 Within the KeyPress event you can check the value of e.KeyChar to see which key was pressed. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
HSN Posted May 10, 2005 Author Posted May 10, 2005 Oh, that was really helpfull. Thank you for your assistant. Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.