简体   繁体   中英

Open new windows form window, closes immediately

I am trying to open a new windows form, however it seem to close immediately every time. it works if i use ShowDialog() instead of Show(), but that is not my intention.

class Forms
{
    Main mainForm;
    Thread mainThread;

    public Forms()
    {

    }
    private void ThreadProc()
    {
        try
        {
            mainForm = new Main();
            mainForm.Show();

        }
        catch {  }
    }
    public void startMain()
    {
        mainThread = new Thread(new ThreadStart(ThreadProc));
        mainThread.SetApartmentState(ApartmentState.STA);
        mainThread.Start();
    }
}

The problem is your mainThread does not run any message loop (that is responsible to react to all the GUI-related messages like resizing, button clicks, etc...), and so after calling mainForm.Show() the thread finishes.
In fact winforms applications usually start like this:

Application.Run(new MainForm());

where, as you can see in the MSDN documentation , Application.Run starts a standard message loop in the current thread and shows the form.

If you use ShowDialog() it works because modal forms run their own message loop internally.

I don't know what you are trying to accomplish but ShowDialog might be the easiest solution; in case you don't like it just replace your mainForm.Show with Application.Run(mainForm) and it should work.

You would need to use Application.Run to start the application message loop, otherwise the program would act like a console app and close once its code has finished executing.

Add using System.Windows.Forms; to the top of the class.

Then change mainForm.Show(); to Application.Run(mainForm); inside ThreadProc.

You should use :

Application.Run(new MainForm());

Begins running a standard application message loop on the current thread, and makes the specified form visible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM