Application.Run() 和 Form.ShowDialog() 有什么区别? [英] What's the difference between Application.Run() and Form.ShowDialog()?

查看:31
本文介绍了Application.Run() 和 Form.ShowDialog() 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,如果登录成功,我想先显示登录表单,然后显示主表单.目前我正在做这样的事情:

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());

但后来我开始想 - Application.Run() 的重点是什么?为什么不直接做 (new MainForm()).ShowDialog() 呢?有什么不同?什么是实现我想要的正确方法?

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?

推荐答案

Application.Run(Form) 在当前线程上启动消息循环并显示指定的表单.消息循环使表单能够接收 Windows 消息(例如,按键、鼠标点击、油漆失效)以使其显示响应并与用户进行交互.当您在 Form 实例上调用 ShowDialog() 时,它实际上做了类似的事情,并为 ShowDialog 所在的表单创建一个模态消息循环已被调用.

Application.Run(Form) starts a message loop on the current thread and displays the specified form. The message loop enables the form to receive Windows messages (eg, key presses, mouse clicks, paint invalidations) to allow it to appear responsive and have interaction with the user. When you call ShowDialog() on a Form instance, it actually does a similar thing and creates a modal message loop for the form on which ShowDialog has been called.

两次调用没有太大区别.Application.Run 确实添加了一些额外的事件处理,使您能够在主窗体关闭时对资源进行一些整理(请参阅 Application.ThreadExit).

There is not much difference between the two calls. Application.Run does add some extra event handling enabling you to do some tidying up of resources when the main form is closed (see Application.ThreadExit).

推荐的启动 WinForms 应用程序的方法是使用 Application.Run,但我怀疑这更像是一种约定而不是规则.使用 Application.Run 的最大原因是如果你想打开多个非模态表单.您可以使用:

The recommended way to start WinForms applications is using Application.Run, but I suspect this is more of a convention than a rule. The biggest reason to use Application.Run is if you want to open multiple non-modal forms. You can do this using:

new Form().Show();
new Form().Show();
Application.Run();

您无法使用 ShowDialog() 方法实现这一点,因为其中一种形式必须是模态的.

You could not achieve this using the ShowDialog() method as one of the forms would have to be modal.

至于您的问题,如果登录成功,如何显示登录表单,然后显示主表单,我认为您所拥有的没问题:

As for your question of how to show a login form and then the main form if the login is successful, I think what you have is fine:

if (new LoginForm().ShowDialog() == DialogResult.OK)
{
    Application.Run(new MainForm());
}

另一种方法是自己做管道,如果登录成功,在 LoginForm 的关闭事件中打开一个 MainForm 的实例.

The alternative is to do the plumbing yourself and open an instance of MainForm in the closing event of the LoginForm if the login was successful.

这篇关于Application.Run() 和 Form.ShowDialog() 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆