How to force the form focus?
Try this:
this.BringToFront();
this.Activate();
You need to show the form first - use the Show()
method:
var form = new loginForm();
form.Show();
Edit: (updated question)
For an existing form calling Activate()
might be more appropriate, this also brings the form to the front:
private void button1_Click(object sender, EventArgs e)
{
var form = new loginForm();
if (Application.OpenForms[form.Name] == null)
{
form.Show();
}
else
{
Application.OpenForms[form.Name].Activate();
}
}
If the form is minimized you need to subscribe to the Activated
event to change your window state to FormWindowState.Normal
:
private void loginForm_Activated(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Normal;
}
it should be
private void button1_Click(object sender, EventArgs e) {
var form = new loginForm();
if (Application.OpenForms[form.Name] == null) {
form.Show();
} else {
Application.OpenForms[form.Name].Focus();
}
}