I want to show a form, but I don't want any of the controls focused. For example, right now when the form is shown, the button with tabindex 0 is focused. I want the form itself, not a button, to be focused, so that if the user accidentally hits a key it won't do anything. Is this possible? Thanks!
no you can't. There's a Workaround BTW. Add an hidden control to the form (a textbox for example) and do
TextBox1.Focus();
in the Form_Shown or Form_Load event.
You can set the TabStop property to false for each control but you won't be able to tab through the controls then. That may or may not be a good solution for you but it should keep any of the controls from receiving input until the user clicks on it.
You can MyInvisibleLabel.Select();
in _Load
or, if you have one, just focus the Exit/Cancel/Close button.
Try this: Add a Panel
control to your form and keep the default settings. The panel can have any size and be positioned anywhere. I'll call this member m_panel
. In your constructor, set your form's ActiveControl
property to m_panel
. Lastly, make sure that the panel's TabStop
property is set to false
(which it is by default).
When the form loads, m_panel
will get the focus. However, since the panel has no border and has the same color as the form background, there is no indication that it exists, so you can effectively say that the form itself has focus, as you wanted. When the user first hits Tab or clicks in a control, the panel will be out of the equation (since TabStop
is false
) and things will work as normal.
Note: you can also use an empty Label
rather than a Panel
, whatever suits you. You can even use one of your existing labels. Remember to use ActiveControl
to specify the control of interest, or focus it explicitly by calling Focus
, since it will not get focus automatically.
vaitrafra's answer is sufficient, but if you happen to have a label on your form, you could just set the focus to that as well. The accepted answer here: http://stackoverflow.com/questions/1140250/how-to-remove-focus-from-a-textbox-in-c-winforms provides a bit more insight into why you can't ensure that every control on the form does not have the focus.
You should likely place focus somewhere relatively harmless initially, such as the "Cancel" button if your form includes such a thing.
A workaround that I have testet;
private void Form1_Shown(object sender, EventArgs e)
{
textBox1.TabStop = false;
textBox1.Focus();
textBox1.Left = -300;
}
This "hides" the textbox with focus by moving it out of the visible area. By doing it in this hackish manner, the textbox retains the ability to have focus.
[edit] This (obviously) requires you to have a textbox named textBox1 on your form that is not used for anything else.