0

I have a Windows.Form where I override the OnKeyDown

override protected void OnKeyDown(KeyEventArgs e) {
    // do things on specific key presses
} 

This works all fine, until I add my Button

class MyWinForm : Form {
    static System.Windows.Forms.Timer Timer = new System.Windows.Forms.Timer();
    static EventHandler EveryTick;
    private System.Windows.Forms.Button button1;

    public MyWinForm() {
         Width = 300;
         Height = 300;
         Text = "MyWinForm";
         this.button1 = new System.Windows.Forms.Button();
         this.button1.Text = "Start";
         this.button1.Size = new System.Drawing.Size(100,50);
         this.button1.Location = new System.Drawing.Point(10, Height -80);
         this.button1.Click += new System.EventHandler(ButtonClick);
         this.Controls.Add(this.button1);
    }
    static void Main() {
         // Some more stuff is happening here
         Application.Run(new MyWinForm());
    }

As soon as I add this.Controls.Add(this.button1); my OnKeyDown doesn't work anymore.

kayleeFrye_onDeck
  • 6,648
  • 5
  • 69
  • 80
Andreas Hubert
  • 381
  • 6
  • 18

1 Answers1

3

All keyboard events always go to the control that has the focus. In a form without any control, it's the form itself that receives all keyboard events, unless you set the property KeyPreview to true.

Before adding the button, the event on the form is the only candidate to handle the event, but after adding the button, by default, it becomes the receiver of all events. Setting KeyPreview to true restores the form as the receiver of all keyboard events.

Alejandro
  • 7,290
  • 4
  • 34
  • 59