winforms - 在调用 Application.Run() 之前关闭(退出)和应用程序?

标签 winforms visual-studio c#-4.0

我无法理解如何关闭 C# .NET winforms 应用程序。我想做的是:

显示一个表单以允许用户按照自己的意愿设置环境 如果用户按下“确定”按钮,则执行一些逻辑来设置应用程序环境(实例化对象等) 如果用户按“取消”或关闭窗口,则关闭应用程序。

问题是,我在主(第一个)表单之前调用环境设置表单。这是最近的需求变更,我不想从一开始就重新编写代码。

我的代码(应该比我的小序言更有意义)是:

    public MainForm()
    {
        InitializeComponent();
        //Get the user to set-up the environment (load specific config files, etc)

        environmentSetupForm newEnvrionmenSetupForm = new environmentSetupForm ();
        if (newEnvrionmenSetupForm .ShowDialog() == DialogResult.OK)
        {
            newEnvrionmenSetupForm .Close();
            //some logic based on what the user selected on the set-up form
        }
        else
        {
            //Since the user didn't set-up the environment correctly (there
            //was a message box, informing them and giving them another
            //shot at it), exit out of the application.
            Application.Exit();
        }
    }

我唯一的问题是,在Application.Exit()之后,堆栈跳回到Program.cs并执行

        Application.Run(new MainForm());

因此主窗体(和应用程序)无论如何都会运行。有没有更好的方法来完成我想做的事情?

编辑:为了清楚起见,我的program.cs代码如下:

   using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Windows.Forms;

   namespace myNamespace
   {
      static class Program
      {
      /// <summary>
      /// The main entry point for the application.
      /// </summary>
      [STAThread]
        static void Main()
        {
          Application.EnableVisualStyles();
          Application.SetCompatibleTextRenderingDefault(false);
          Application.Run(new MainForm());
        }
     }
   }

最佳答案

表单的构造函数及其 OnLoad 或 Load 事件都不是放置此代码的好地方。构造函数由于 Main() 方法中的 new MainForm() 语句(在 Application.Run() 调用之前)而运行。 Load 事件被触发是因为 Application 类在 Application.Run() 进入消息循环之前调用隐藏在框架代码中的 Show() 方法。在消息循环开始运行之前,Application.Exit() 无法执行任何操作。

解决方法是将此代码移至 Program.cs 中的 Main() 方法。使其看起来与此类似:

    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        MainForm main;            
        using (var dlg = new environmentSetupForm()) {
            if (dlg.ShowDialog() != DialogResult.OK) return;
            // Use dlg values
            //...
            main = new MainForm();
            // Make main form show up at the same location
            main.StartPosition = FormStartPosition.Manual;
            main.Location = dlg.Location;
        }
        Application.Run(main);
    }

关于winforms - 在调用 Application.Run() 之前关闭(退出)和应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8879563/

相关文章:

c# - App.config Windows 窗体应用程序的转换

c# - WinForms:DataGridView - 编程排序

c# - 检查控件是否为 TabControl 中的文本框

C#如何编写泛型方法

.net - 如何在 .net 4 中找到并行性的热点?

C# 增强方法重载解析

c# - 使用 C# WebBrowser 禁用历史记录和用户凭据?

asp.net - 从命令行运行时,Docker 容器不起作用

c# - 是否可以使用 C# 更改 Visual Studio 中的默认文档标题

.net - 命名空间在其他项目中不可用