Perform a default action without an accept button in C#

[default action]

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 Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in controls, user interface and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *