简体   繁体   English

KeyPress和KeyDown事件

[英]KeyPress and KeyDown events

Hello I'm trying to make a program in WF that uses the KeyPress event. 您好,我正在尝试使用WF创建一个使用KeyPress事件的程序。 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. 有人还告诉我KeyDown事件可以工作,但我也不知道如何使用它们。

You need to set Form.KeyPreview 您需要设置Form.KeyPreview

eg In your form 例如以您的形式

this.KeyPreview =true;

Don't use while(true) in an event handler. 不要在事件处理程序中使用while(true) 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: 将按下的键与实际字符而不是ASCII码进行比较似乎也更干净:

    switch (e.KeyChar)
    {
        case 'D':
            MessageBox.Show("Test");
            break;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM