How to force the form focus?

自古美人都是妖i 提交于 2019-12-18 19:29:40

问题


How can I force the focus of an form? .Focus() is not working for me.

private void button1_Click(object sender, EventArgs e) {
   var form = new loginForm();
    if (Application.OpenForms[form.Name] == null) {
           form.Show();
    } else {
         form.Focus();
    }
}

What am I doing wrong?


回答1:


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();
    }
}



回答2:


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;
}



回答3:


Try this:

this.BringToFront();
this.Activate();



回答4:


On start of the form we add
this.BringToFront(); this.Activate();



来源:https://stackoverflow.com/questions/8461005/how-to-force-the-form-focus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!