user586399
user586399

Reputation:

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 Focused. Whenever I disable buttonStart, it fires.

NOTES:

Upvotes: 0

Views: 1165

Answers (1)

Glory Raj
Glory Raj

Reputation: 17701

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

Upvotes: 2

Related Questions