Alex Taylor
Alex Taylor

Reputation: 21

Is there a benefit to calling Application.Run in a C# Winforms Application?

I'm designing a set of sequential modal dialogs. The following code seems to work, with no problems whatsoever. What would I gain by creating a custom ApplicationContext and passing it to Application.Run or, alternatively, passing the last modal dialog to Application.Run in lieu of calling ShowDialog? (Edit: Obviously calling Application.Run(...) would replace Application.Exit())

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Form1 f = new Form1();
        f.ShowDialog(); //Show a modal dialog
        Form1 f2 = new Form1();
        f2.ShowDialog(); //Chain another modal dialog
        Application.Exit();
    }

Upvotes: 2

Views: 357

Answers (1)

Hans Passant
Hans Passant

Reputation: 942257

No, if you want to structure your program this way then there is no point in calling Application.Run(). No point in calling Application.Exit() either, it already terminates when your Main() method ends.

The Form.ShowDialog() method already calls Application.Run() under the hood. The basic way by which a dialog becomes modal and why your code does not immediately resume to the next statement after ShowDialog(). Like it does when you use Show() instead. Not until that dispatcher loop ends, triggered by closing the form or setting the DialogResult property.

Which is something you normally need to test for by checking the ShowDialog() return value. Right now the user has no good way to end your app when the first window appears, that can be pretty confusing.

Upvotes: 1

Related Questions