首页 > 解决方案 > 带有 OnKeyDown 和其他控件的 Winforms

问题描述

我有一个 Windows.Form 我覆盖OnKeyDown

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

这一切正常,直到我添加我的按钮

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

一旦我添加this.Controls.Add(this.button1);我的 OnKeyDown 就不再工作了。

标签: c#winforms

解决方案


所有键盘事件总是转到具有焦点的控件。在没有任何控件的表单中,接收所有键盘事件的是表单本身,除非您将属性KeyPreview设置为true.

在添加按钮之前,表单上的事件是唯一处理事件的候选者,但是在添加按钮之后,默认情况下,它成为所有事件的接收者。设置KeyPreviewtrue将表单恢复为所有键盘事件的接收者。


推荐阅读