[RESOLVED] [2.0] Always trigger AcceptButton even when another button has focus
I have a Windows form and a button that should always be triggered whenever the user presses Enter. I can set the AcceptButton property but if another button is clicked and keeps the focus, then this does no good.
Is there a way to always click a certain button whenever the Enter key is pressed?
Re: [2.0] Always trigger AcceptButton even when another button has focus
In your form's keydown event, check to see if e.keycode = keys.enter. Then call Button5_Click()
Re: [2.0] Always trigger AcceptButton even when another button has focus
Quote:
Originally Posted by mendhak
In your form's keydown event, check to see if e.keycode = keys.enter. Then call Button5_Click()
That only works when the form is first created and nothing has focus. If a button is ever clicked and gets focus, every Enter key press triggers the button click event.
Re: [2.0] Always trigger AcceptButton even when another button has focus
It's not possible with a standard Button. Even if you set the form's KeyPreview property to True the form will not raise keyboard events for the Enter key when a Button has focus. I'm guessing that you would have to inherit the Button class and reverse the result of the IsInputKey function for the Enter key. I haven't checked but I'm guessing it returns True and you'd have to return False instead.
Re: [2.0] Always trigger AcceptButton even when another button has focus
OOh.. yes.
Let's see what can be found...
Re: [2.0] Always trigger AcceptButton even when another button has focus
Code:
protected override bool ProcessDialogKey(Keys keyData)
{
if (keyData == Keys.Enter)
{
button3_Click(null, null);
return false;
}
else
{
return base.ProcessDialogKey(keyData);
}
}
private void button3_Click(object sender, EventArgs e)
{
Console.WriteLine("Button3");
}
Re: [2.0] Always trigger AcceptButton even when another button has focus
Rather than this:
CSharp Code:
button3_Click(null, null);
you should do this:
CSharp Code:
this.button3.PerformClick();