Fire Form KeyPress事件

我有一个C#winform,我有一个按钮。
现在,当我运行我的应用程序时,该按钮会自动获得焦点。

问题是我的表单的KeyPress事件不起作用,因为按钮是聚焦的。

我试过this.Focus();FormLoad()事件上,但仍然没有KeyPress事件。

您需要覆盖表单的ProcessCmdKey方法 。 这是您通知子控件具有键盘焦点时发生的关键事件的唯一方式。

示例代码:

 protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { // look for the expected key if (keyData == Keys.A) { // take some action MessageBox.Show("The A key was pressed"); // eat the message to prevent it from being passed on return true; // (alternatively, return FALSE to allow the key event to be passed on) } // call the base class to handle other key events return base.ProcessCmdKey(ref msg, keyData); } 

至于为什么this.Focus()不起作用,这是因为表单本身不能具有焦点。 特定控件必须具有焦点,因此当您将焦点设置为窗体时,它实际上将焦点设置为可以接受具有最低TabIndex值的焦点的第一个控件。 在这种情况下,这是你的按钮。

尝试将Form的KeyPreview属性设置为True。

在主窗体上设置keyPreview = true

我会使用以下之一:

  1. 将按钮的TabIndex属性设置为0。

  2. 将按钮的IsDefault属性设置为true – 因此,按ENTER键时将触发该属性。

我有同样的问题,我知道很久以前就回答了这个问题,但我对这个问题的解决方案来自另一个堆栈溢出问题,其中我的唯一按钮抓住并保持焦点。 我接受了用户的建议并创建了一个无法获得焦点的按钮。

也许有人会觉得这很有用:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace I2c_Programmer { class NoSelectButton : Button{ public NoSelectButton() { SetStyle(ControlStyles.Selectable, false); } } } 

进入设计器,创建按钮并使用新类“new NoSelectButton();”切换出新的System …按钮。