This seems very basic but have not been able to find any information on it.
I have a button in a Windows form that is the AcceptButton and should always have the AcceptButton behavior i.e. pressing the enter key when focus is on the form should always click the button and it should always be highlighted to show that action is available.
However, when a different button is clicked, that button is now highlighted and when enter is pressed, that button is clicked instead of the AcceptButton.
Here is my test application that shows the behavior:
public Form1()
{
InitializeComponent();
AcceptButton = btnAccept;
}
private void btnAccept_Click(object sender, EventArgs e)
{
MessageBox.Show("You clicked the accept button");
Debug.WriteLine(AcceptButton == btnAccept ? "true" : "false");
}
private void btnNothing_Click(object sender, EventArgs e)
{
Debug.WriteLine(AcceptButton == btnAccept ? "true" : "false");
}
private void btnBrowse_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
Debug.WriteLine(AcceptButton == btnAccept ? "true" : "false");
}
When the application launches initially - it works as I expect, btnAccept is highlighted and enter clicks that button.
However, when I click btnNothing or btnBrowse, that button is now highlighted and pressing enter clicks that button again. Additionally, the debug lines always show that btnAccept is still the AcceptButton even when the enter button is clicking a different button.
The CanFocus property that Button inherits from Control looks promising, but this property is read only.
What's going on here? Is there some property I can use to change this behavior?
Edit
Ended up going with this solution based on @AWinkle 's answer:
public Form1()
{
InitializeComponent();
AcceptButton = btnAccept;
}
private void btnAccept_Click(object sender, EventArgs e)
{
MessageBox.Show("You clicked the accept button");
}
private void btnNothing_Click(object sender, EventArgs e)
{
Button acceptButton = (Button)this.AcceptButton;
acceptButton.Select();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
Button acceptButton = (Button)this.AcceptButton;
acceptButton.Select();
}