我有一个C#winform,我有1个按钮.
现在,当我运行我的应用程序时,该按钮会自动获得焦点.
现在,当我运行我的应用程序时,该按钮会自动获得焦点.
问题是我的表单的KeyPress事件不起作用,因为按钮是聚焦的.
我试过这个.Focus();在FormLoad()事件上,但仍然没有KeyPress事件.
解决方法
您需要覆盖表单的
ProcessCmdKey
method.这是您通知子控件具有键盘焦点时发生的关键事件的唯一方式.
示例代码:
- 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值的焦点的第一个控件.在这种情况下,那是你的按钮.