user7667690
user7667690

Reputation:

How to Focus to another form in C#

I have a program which opens two forms and I want when I click on Form1 then Focus on Form2.

private void Form1_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2();
    frm2.Focus();
}

But this doesn't work, what's wrong in my code?

EDIT: I found already answered Here by @moguzalp at the comments

Upvotes: 0

Views: 3095

Answers (4)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186823

If you can have a form opened, try finding it:

using System.Linq;

...

// Do we have any Form2 instances opened?
Form2 frm2 = Application
  .OpenForms
  .OfType<Form2>()
  .LastOrDefault(); // <- If we have many Form2 instances, let's take the last one 

// ...No. We have to create and show Form2 instance
if (null == frm2) {
  frm2 = new Form2();
  frm2.Show(); 
}
else { // ...Yes. We have to activate it (i.e. bring to front, restore if minimized, focus)
  frm2.Activate();
}

Upvotes: 0

Ofir Winegarten
Ofir Winegarten

Reputation: 9365

If you already opened the form elsewhere, then this code will not work as it's a new instance of Form2 and not the one that is opened.

You will have to keep a reference to the form that is opened, and then use Focus or might be better Activate on it.

if the form is opened from within Form1 then:

  1. Add a field for holding current reference of Form2
  2. Save it when showing the form.
  3. Use it when focusing

    private Form2 currentForm2;
    ....
    this.currentForm2 = new Form2();
    this.currentForm2.Show();
    ...
    ...
    this.currentForm2.Activate();
    

Upvotes: 0

madoxdev
madoxdev

Reputation: 3890

First of all that Form2 is never visible.

    private void Form1_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2();
    frm2.Show();
    frm2.Focus();
}

If that Form is visible though with your code, that means you need to get same reference and call Focus() against it.


EDIT:


Then you need to have a reference to that Form. At some point you created that Form and assigned it to a vairable/field or anything like that.

You need to call Focus or Activate against it.

Example:

Inside Form1 when you create a Form2 instance:

public class Form1 : Form 
{
   private Form _frm2;


   //That code you probably have somewhere. You need to make sure that this Form instance is accessible inside the handler to use it.
   public void Stuff() {
     _frm2 = new Form2();
     _frm2.Show();
   }

    private void Form1_Click(object sender, EventArgs e)
    {
        _frm2.Focus(); //or _frm2.Activate();
    }


}

Upvotes: 1

pitersmx
pitersmx

Reputation: 957

If you want to Show your frm2, you should call frm2.Show(); or frm2.ShowDialog();.

Also, before 'Show' call you can set frm2.TopMost = true; if you want this form to be on the top.

So it could be:

private void Form1_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2();
    frm2.TopMost = true;
    frm2.Show();
}

Upvotes: 0

Related Questions