Home > Mobile >  Focus winform after application.run
Focus winform after application.run

Time:09-17

I have 2 winforms in an application in visual studio. The first one is kind of a loading screen, making sure there are no connection problems, then a second winforms opens, which would be a login form. I use this method to close the first form and open the second one:

this.Close();
th = new Thread(opennewform); // [opennewform thread: Application.Run(new Login());]
th.SetApartmentState(ApartmentState.STA);
th.Start();

and it works fine, but when the second form opens it loses focus. I've tried adding this.Activate, this.BringtoFront, this.Show to the second form, but it doesn't work. And what I need is after the first form closes and the second one opens, this second form is the "active" form, so it always pops up. I also needed to use the close/thread method so that the first form really closes and not just this.hide(); but actually stays in the background. Thanks in advance for the help.

CodePudding user response:

You do not need to create a new thread. Instead, change the start code to something like this

[STAThread]
static void Main()
{
    Application.SetHighDpiMode(HighDpiMode.SystemAware);
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    var form1 = new Form1();
    form1.Show();
    Application.Run();
}

I.e., remove the first form from Application.Run(), so that the application does not exit when this form closes.

Then open the second form with

Close();
var form2 = new Form2();
form2.Show();

Now, the application will not exit automatically when you close any form. Therefore, you must exit it explicitly with Application.Exit();, e.g. in the FormClosed event of the second form.

CodePudding user response:

try:

Form2 f2 = new Form2();
this.Hide();
f2.ShowDialog();
this.Close();
  • Related