7

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

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

我已经尝试过this.Focus();事件FormLoad(),但 KeyPress 事件仍然不起作用。

4

5 回答 5

11

您需要覆盖表单的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值的焦点的控件。在这种情况下,这是您的按钮。

于 2011-03-31T12:09:28.697 回答
5

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

于 2011-03-31T12:01:15.003 回答
1

在主窗体上设置 keyPreview = true

于 2012-06-07T04:03:11.440 回答
0

我会使用以下之一

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

  2. 将按钮的IsDefault属性设置为 true - 因此,当按下ENTER键时将触发它。

于 2011-03-31T12:12:19.487 回答
0

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

也许有人会发现这很有用:

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

于 2013-07-19T13:53:28.080 回答