Title: Perform a default action without an accept button in C#
Normally to give a form a default action, you set the form's AcceptButton property to a button that should be triggered when the user presses Enter. But what if you don't want a visible button on the form? You can catch keyboard events and look for the Enter key, but there's an easier way.
Set the form's AcceptButton property to a button as usual. You can't set the button's Visible property to false because then it won't fire events. However, you can set its position so it isn't visible on the form. You should also set the button's TabStop property to false so the user doesn't tab onto it and become confused.
When it starts, this example uses the following code to prepare to use the btnAccept button.
private void Form1_Load(object sender, EventArgs e)
{
this.AcceptButton = btnAccept;
btnAccept.TabStop = false;
btnAccept.Left = -btnAccept.Width;
}
This code simply sets the form's AcceptButton property, sets the button's TabStop property to false, and moves the button so it sits off the left edge of the form where it can't be seen.
Download the example to experiment with it and to see additional details.
|