0

Hello I'm trying to make a program in WF that uses the KeyPress event. I've written the following code:

 private void Form1_KeyPress(object sender, KeyPressEventArgs e)
   {
     while (true)
     {
         switch (e.KeyChar)
         {
                    case (char)68:
                        MessageBox.Show("Test");
                        break;
         }
      }
}

But when I execute the program and press the key the message box doensn;t appear. Does anyone have any suggestions or knows how to fix this? I've also been told that a KeyDown event could work but I don't know how to work with those either.

1
  • 2
    Is this real code? It will hang your app independently of the actual key. Commented Apr 24, 2014 at 15:07

2 Answers 2

3

Don't use while(true) in an event handler. It will loop infinitely.

Just do

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    switch (e.KeyChar)
    {
        case (char)68:
            MessageBox.Show("Test");
            break;
    }
}

Also is seems cleaner to compare the pressed key to the actual character rather than the ASCII code:

    switch (e.KeyChar)
    {
        case 'D':
            MessageBox.Show("Test");
            break;
    }
Sign up to request clarification or add additional context in comments.

Comments

3

You need to set Form.KeyPreview

e.g. In your form

this.KeyPreview =true;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.