C# Textbox Keypress Control Help
I have a standard textbox that I want to perform an action on a keypress. I have this code currently:
private void idTextEdit_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter/Return)
{
e.Handled = true;
SearchButtonClick(sender, EventArgs.Empty);
}
}
The problem is, I have tried both Enter and Return up there which is the reaso开发者_高级运维n for that. It is only firing that check for normal keys that are not like shift, control, etc. How can I design this so that it will pick up and use the enter/return key in the same way?
You should use the KeyDown
event instead:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Return)
{
//...
}
}
If it for some reason has to be KeyPress
, you can use (char)13
or '\r'
for your check, though I doubt that would work well on a non-Windows OS.
if (e.KeyChar == '\r')
You cannot just cast Keys.Return
to a char
, because it's a bitflag enum and doesn't just hold the corresponding ASCII code.
Use the KeyDown event instead.
精彩评论