armin
armin

Reputation: 2025

Why doesn't winform open without Application.Run()?

I tried to show a winform with the code below but it opens and immediately closes. I couldn't understand the reason for this.Any ideas?

[STAThread]
    static void Main()
    {
        try
        {
            AppDomain.CurrentDomain.UnhandledException += AllUnhandledExceptions;
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);

            Test testWin = new Test();
            testWin.Show();
        }
        catch (Exception ex)
        {
            Logger.Error("Main : " + ex.Message, typeof(Program));
        }
    }

Its works fine if I replace testWind.Show() with Application.Run(testWin).

Upvotes: 1

Views: 247

Answers (2)

sh_kamalh
sh_kamalh

Reputation: 3901

You should use ShowDialog method instead.

Test testWin = new Test();
testWin.ShowDialog();

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503280

Application.Run runs the message loop which basically handles UI events etc until all the visible windows have shut. The method blocks until the message loop has shut down.

You need that message loop to be running in order to keep the UI up, basically - whereas Show() will just display the window, but not run any kind of message loop itself, and not block - do the Main method completes, and the application terminates.

Upvotes: 2

Related Questions