Tim van Gool
Tim van Gool

Reputation: 305

KeyPress and KeyDown events

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.

Upvotes: 0

Views: 171

Answers (2)

D Stanley
D Stanley

Reputation: 152491

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;
    }

Upvotes: 3

huMpty duMpty
huMpty duMpty

Reputation: 14460

You need to set Form.KeyPreview

e.g. In your form

this.KeyPreview =true;

Upvotes: 3

Related Questions