简体   繁体   中英

KeyDown event doesn't raise

I have a form with a button in. I want to capture the Form.KeyDown event.

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. Since I have added the PAUSE advantage, the Form.KeyDown event doesn't raise and buttonStart is Focuse d. Whenever I disable buttonStart , it fires.

NOTES:

  • I have set Form.KeyPreview to true , stills doesn't raise
  • I have set Form.AcceptButton to null , stills doesn't raise
  • I have made buttonStart subscriped to Form.KeyDown , stills doesn't.

I hope this will helps you ..


Override IsInputKey behaviour


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. 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

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. 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:

In the Buttons' KeyDown Method try to set these properties:

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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