Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Trying to get theKeyPressEventHandler to work

Status
Not open for further replies.

Salte2

Programmer
Nov 5, 2004
17
0
0
NO
I've created this form, and when the form is visible and some certain keys are pressed, I want certain things to happend. But (so far) they dont...

In the constructor of the form i have this line of code:
Code:
this.KeyPress += new KeyPressEventHandler(KnappTrykket);

and i have this function relating
Code:
private void KnappTrykket(object sender, KeyPressEventArgs e)
{
	if(e.KeyChar == 'k')
	{	//execute some function	}
//some more if/else statements and

	else
	{	//execute some other function}

	e.Handled = true;

}

this would lead med to believe no matter what key is struck something will happend, but nothing happens (in ohter words the 'KnappTrykket'-function is never called. What am i missing here?
 
Have you put a break line / debug point (f9) at the start of the private function to see if the event handler is working?

Im no C# expert, but your event handler has a single parameter in the declaration, and in the funciton body you are specifying 2 parameters. I assume it is legal, else your code wouldnt compile?

And one last thing, I thought event handlers werent in the constructor, but in their own section of the class. (Again, I am probably showing my ignorance, so apologies)

K
 
If you are working with Windows, you've to set Keypress = True in Form properties
 
Thanks a bunch sbdSolna, that did the trick!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top