What's the difference between Application.Run(

2019-01-04 23:42发布

In my application I want to show a login form first and then the main form if the login has been successful. Currently I'm doing it something like this:

var A = new LoginForm();
if ( A.ShowDialog() == DialogResult.OK )
    Application.Run(new MainForm());

But then I started wondering - what's the point of the Application.Run()? Why not just do (new MainForm()).ShowDialog() as well? What's the difference? And what would be the correct way to achieve what I want?

标签: c# winforms
8条回答
我命由我不由天
2楼-- · 2019-01-04 23:48

One key difference is that ShowDialog is usually a modal Dialog. If you wanted to create a user-friendly toolset, you would not want it to be comprised of modal dialog boxes.

Also, Application.Run() accepts more than just a form. It has a few overloads.

As for your application, I do not think it matters much. Application.Run makes sense to me because it denotes the start of your actual Application.

查看更多
▲ chillily
3楼-- · 2019-01-04 23:51

For a more concerete example of a difference:

If your main form is an MDI form, then the behavior on clicking the close button (the 'x' in the upper right, or Alt-F4) is different depending on which method you use to show the form.

With Application.Run(mainForm), the closing event of the child forms run, then the main form's closing event runs.

With mainForm.ShowDialog, the closing event of the main form runs, and the closing event of the child forms do not run.

查看更多
放我归山
4楼-- · 2019-01-05 00:03

The documentation of the overload

public static void Run(
    ApplicationContext context );

has a neat example with a different approach that involves two forms as well.

查看更多
Evening l夕情丶
5楼-- · 2019-01-05 00:04

From my testing I notice that using Application.Run buttons with DialogResult does not close the form (OnFormClosing is not hit) compare to ShowDialog in which the buttons with DialogResult hit OnFormClosing and the close the form.

查看更多
何必那么认真
6楼-- · 2019-01-05 00:06

From MSDN:

This method adds an event handler to the mainForm parameter for the Closed event. The event handler calls ExitThread to clean up the application.

http://msdn.microsoft.com/en-us/library/ms157902.aspx

查看更多
放荡不羁爱自由
7楼-- · 2019-01-05 00:06

From my testing, I noticed this main difference:

When Application.Run is used, the form's Close button (red X) returns DialogResult.None; however, when ShowDialog is used, the Close button produces DialogResult.Cancel.

Does this matter to you? In my code, I was testing for DialogResult.Cancel to determine the exit code of my application. That was broken when the red X was used to close the form. I now test for DialogResult.OK to indicate a successful exit.

        return myForm.DialogResult == DialogResult.OK ? 0 : 1;
查看更多
登录 后发表回答