public void btnClick(object sender, EventArgs e)
{
bool IsMouse = (e is System.Windows.Forms.MouseEventArgs);
// If not mouse, they hit spacebar or enter
}
break button_click event when enter pressed
-
29-06-2022 - |
Question
Is an easy way to cancel click event when user hit enter on button (instead of mouse click on button?)
i have tried with:
private void button3_Click(object sender, EventArgs e)
{
KeyEventArgs ke = e as KeyEventArgs;
if (ke != null)
{
if (ke.KeyCode == Keys.Enter)
{
return;
}
}
}
But ke is null
La solution
Autres conseils
Yes it will be null. because EventArgs
is not KeyEventArgs
KeyEventArgs
will be passed as a parameter to KeyDown
or KeyUp
events. You're messing up things.
You can do something like this
private bool flag = false;
private void button1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
{
flag = true;
}
}
private void button1_Click(object sender, EventArgs e)
{
if (flag)
{
flag = false;
return;
}
//else do original task
}
You can handle KeyPress event for the button and disable or ignore enter key there instead of returning in button click
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if ((keyData & Keys.KeyCode) == Keys.Enter)
{
SendKeys.Send("{Tab}");
return true;
}
return false;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow