Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open new windows form window, closes immediately

Tags:

c#

winforms

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();
    }
}
like image 909
user2725580 Avatar asked Dec 09 '22 10:12

user2725580


2 Answers

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.

like image 165
digEmAll Avatar answered Dec 11 '22 08:12

digEmAll


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.

like image 43
K. S. Avatar answered Dec 11 '22 07:12

K. S.