We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now


Trapping KeyStrokes

Miatchguy asked
Medium Priority
Last Modified: 2012-06-21
I'm trying to trap keystrokes in my C# program and it doesn't seem to be working, can someone tell me what I'm doing wrong? Here is My Code:

private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
                  e.Handled = true;
                        case Keys.Left:
                              lbl1.Text = "Left";
                        case Keys.Up:
                              lbl1.Text = "Up";
                        case Keys.Right:
                              lbl1.Text = "Right";
                        case Keys.Down:
                              lbl1.Text = "Down";
                              e.Handled = true;
Watch Question

Set KeyPreview form property to true.


I did that, but it still doesn't work. The trouble I'm having is in the:
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
part. I put a message box before the case switch and nothing happens when I press a key. Can someone tell me what to do or show me an example of some workning code?

I used the notion of making a key sequence a HotKey

And using the Windows Message Dispatch loop to catch it

It was quick, and easy, and thje code is available in the site!
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview

Place the statement e.Handled = true after the switch block.
Hope this helps.


I actually tried my solution in code before posting it, if that's worth anything.
It worked fine for me.
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a free trial preview!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.