简体   繁体   English

KeyDown事件不会引发

[英]KeyDown event doesn't raise

I have a form with a button in. I want to capture the Form.KeyDown event. 我有一个带有按钮的表单。我想捕获Form.KeyDown事件。

private void buttonStart_Click(object sender, EventArgs e)
{
   if (!this.gameRunning)
   {
       this.buttonStrat.Text = "Pause";
       this.timer1.Enabled = true;
   }
   else
   {
       this.buttonStart.Text = "Continue";
       this.timer1.Enabled = false;
   }
   this.gameRunning = !this.gameRunning;
}

However, I was disabling buttonStart without supporting PAUSE and it was working nice. 但是,我在没有支持PAUSE的情况下禁用了buttonStart ,它运行良好。 Since I have added the PAUSE advantage, the Form.KeyDown event doesn't raise and buttonStart is Focuse d. 由于我添加了PAUSE优势,因此Form.KeyDown事件不会引发,而buttonStartFocuse d。 Whenever I disable buttonStart , it fires. 每当我禁用buttonStart ,它都会触发。

NOTES: 笔记:

  • I have set Form.KeyPreview to true , stills doesn't raise 我已将Form.KeyPreview设置为true ,stills不会引发
  • I have set Form.AcceptButton to null , stills doesn't raise 我已将Form.AcceptButton设置为null ,stills不会引发
  • I have made buttonStart subscriped to Form.KeyDown , stills doesn't. 我已经将buttonStart订阅了Form.KeyDown ,但仍然没有订阅。

I hope this will helps you .. 我希望这会对你有所帮助..


Override IsInputKey behaviour 覆盖IsInputKey行为


You must override the IsInputKey behavior to inform that you want the Right Arrow key to be treated as an InputKey and not as a special behavior key. 您必须覆盖IsInputKey行为,以通知您希望将右箭头键视为InputKey而不是特殊行为键。 For that you must override the method for each of your controls. 为此,您必须覆盖每个控件的方法。 I would advise you to create your won Buttons, let's say MyButton 我建议你创建你赢得的按钮,让我们说MyButton

The class below creates a custom Button that overrides the IsInputKey method so that the right arrow key is not treated as a special key. 下面的类创建一个自定义Button,它覆盖IsInputKey方法,因此右箭头键不会被视为特殊键。 From there you can easily make it for the other arrow keys or anything else. 从那里你可以轻松地为其他箭头键或其他任何东西。

    public partial class MyButton : Button
    {
        protected override bool IsInputKey(Keys keyData)
        {
            if (keyData == Keys.Right)
            {
                return true;
            }
            else
            {
                return base.IsInputKey(keyData);
            }
        }
    }

Afterwards, you can treat your keyDown event event in each different Button or in the form itself: 之后,您可以在每个不同的Button或表单本身中处理您的keyDown事件事件:

In the Buttons' KeyDown Method try to set these properties: 在按钮的KeyDown方法中尝试设置这些属性:

private void myButton1_KeyDown(object sender, KeyEventArgs e)
{
  e.Handled = true;
  //DoSomething();
}

-- OR -- - 要么 -

handle the common behaviour in the form: (do not set e.Handled = true; in the buttons) 处理表单中的常见行为:(不要设置e.Handled = true;在按钮中)

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    //DoSomething();
}

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

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