How to force the form focus?

后端 未结 5 1435
无人共我
无人共我 2021-01-04 08:37

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         


        
相关标签:
5条回答
  • 2021-01-04 09:06

    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;
    }
    
    0 讨论(0)
  • 2021-01-04 09:06

    None of the previous answers worked for me, but this does:

    protected override void OnShown(EventArgs e)
    {
        Focus();
    }
    

    None of the focusing methods worked if called before this event. Hope it helps.

    0 讨论(0)
  • 2021-01-04 09:09

    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();
        }
    }
    
    0 讨论(0)
  • 2021-01-04 09:14

    Try this:

    this.BringToFront();
    this.Activate();
    
    0 讨论(0)
  • 2021-01-04 09:20

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

    0 讨论(0)
提交回复
热议问题