Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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?

  • Administrators
Posted

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.

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

Posted
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.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...