Click here to Skip to main content
12,300,379 members (51,775 online)
Rate this:
Please Sign up or sign in to vote.
See more: C# keypress

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.

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


EDIT: I've tried the code with a different key (Left) and it still fails to work correctly...
Posted 12-Oct-12 6:38am
Edited 12-Oct-12 6:46am
Marcus Kramer 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.
Marcus Kramer 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. :)
Wes Aday 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!
Marcus Kramer 12-Oct-12 12:49pm
If you place a breakpoint in the handler, does it get hit?
Rate this: bad
Please Sign up or sign in to vote.

Solution 1


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
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).
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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

and form have focus.

Happy Coding!
Smile | :)

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.160525.2 | Last Updated 12 Oct 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100