Click here to Skip to main content
15,893,722 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I am new to C# programming and I'm trying to make a little test application. When you press the D key, a message box will pop up. However, it doesn't seem to be working. Please may you see if you can find the problem and fix it.

C#
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.D)
    {
        MessageBox.Show("You pressed D!");
    }

}


Remember to please tell me the problem in simple terms because I really don't understand C# too well yet...

Thanks!

EDIT: I've tried the code with a different key (Left) and it still fails to work correctly...
Posted
Updated 12-Oct-12 6:46am
v2
Comments
fjdiewornncalwe 12-Oct-12 12:39pm    
Are you sure you aren't pressing 'd' instead of 'D'?
OrangeFlash81 12-Oct-12 12:44pm    
Erm... I've tried pressing both a capitalized D and a lowercase D on my keyboard and they don't work, if that's what you meant.
fjdiewornncalwe 12-Oct-12 12:48pm    
I did. I just mention it as a comment because I know too many people who have done that and you didn't mention in your question that you had so I was doing the default "Is it plugged in" support response. :)
[no name] 12-Oct-12 12:48pm    
If you mean "does not work" as in the event is not fired, you need to set your KeyPreview property to True on your form.
OrangeFlash81 12-Oct-12 12:51pm    
Thanks! Solved!

if it is windows application,
then check KeyPreview property of your form it should be True

and form have focus.

Happy Coding!
:)
 
Share this answer
 
Hi,

The possible cause is your keyboard focus is not on the form. if you have added more number of controls on your form and your tab focus is on some control then it will not fire the event.

If you want to fire this event, make sure your current focus is on the form.

Hope you got the idea.

Best luck
 
Share this answer
 
Comments
OrangeFlash81 12-Oct-12 12:48pm    
Ahh, okay, I see what you mean. If I want a 'universal focus' if you will (it doesn't matter what you are focused on), what should I use?
AmitGajjar 12-Oct-12 12:55pm    
there can be two option. when you need to capture the keypress event either you focus your current tab on the form or you can create system level programming to read each key strokes(See here).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900