Home > Software engineering >  How do I launch a new form in front of my original form in C# Windows Forms?
How do I launch a new form in front of my original form in C# Windows Forms?

Time:12-21

I am building a C# Windows Forms app in Visual Studio 2022. I've added a button on Form1 (form displayed on launch), call it the addWorkersButton.

private void addWorkersButton_Click(object sender, EventArgs e)
    {
        ExternalDeptEmployeeForm f2 = new ExternalDeptEmployeeForm();
        f2.Show();   
        f2.BringToFront();
    }

However, I'm still getting the form launched from the button click to appear behind Form1. I've tried out combinations of several of the available methods to try and achieve this to no avail:

private void addWorkersButton_Click(object sender, EventArgs e)
    {
        ExternalDeptEmployeeForm f2 = new ExternalDeptEmployeeForm();
        f2.Show();
        this.SentToBack();  
    }

From other posts I have found, these examples provided appear to work in a lot of instances, so I'm just not sure what is different in my project that would be preventing this.

I've also attempted to add the newly instantiated form f2 to be owned by the original form (Form1) and then Show() it. I did this because according to the docs, Microsoft says about the AddOwnedForm() method: "Owned forms are also never displayed behind their owner form." You can find this under Remarks here: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.form.addownedform?view=windowsdesktop-7.0

In my Program.cs file, in the Main() method, I am running an instance of Form1, which then appears to require an instance of Form1 to exist during runtime in order for the application to continue to run:

internal static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

If this is an issue, what is the work-around? To me, it seems that there should be no issue displaying f2 in from of Form1, because I am not trying to close it or end that process in any way. Any insight would be appreciated.

CodePudding user response:

Use:

f2.Show(this);

Instead of calling Control.Show(), (i.e. f2.Show() with no arguments), you should call Form.Show(IWin32Window) and pass the owning window/form as the argument (i.e. f2.Show(this)) and the f2 form will be shown in front of this form. Also, this form will be the owner of the f2 form.

  • Related