问题
I have a C# winform, on which I have 1 button.
Now, when I run my application, the button gets focus automatically.
The problem is KeyPress
event of my form does not work because the button is focused.
I have tried this.Focus();
on FormLoad()
event, but still the KeyPress event is not working.
回答1:
You need to override the ProcessCmdKey method for your form. That's the only way you're going to be notified of key events that occur when child controls have the keyboard focus.
Sample code:
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);
}
As for why this.Focus()
doesn't work, it's because a form can't have the focus by itself. A particular control has to have the focus, so when you set focus to the form, it actually sets the focus to the first control that can accept the focus that has the lowest TabIndex
value. In this case, that's your button.
回答2:
Try setting the Form's KeyPreview property to True.
回答3:
Set keyPreview = true on main form
回答4:
I would use one of the following:
Set the TabIndex property of the button to 0.
Set the IsDefault property of the button to true - So, It will be fired when pressing the ENTER key.
回答5:
I had this same problem and I know this question was answered long ago, but my solution to this problem came from another stack overflow question in which my only button grabbed and kept focus. I accepted the users advice and created a button which couldn't get focus.
Maybe someone will find this useful:
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);
}
}
}
Go into your designer, where the button is created and switch out the new System...button with your new class "new NoSelectButton();"
来源:https://stackoverflow.com/questions/5499463/fire-form-keypress-event