【问题标题】:C# - How to Close a From and Application.RunC# - 如何关闭 From 和 Application.Run
【发布时间】:2020-03-28 19:55:09
【问题描述】:

这个简单的代码可以防止应用程序关闭

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Thread TH = new Thread(Run);
        TH.Start();
    }

    void Run()
    {
        Application.Run();
    }

另一方面,我可以通过以下方式阻止它:

        Application.Exit();

但是,当按下 Form 上的 [X] 按钮时,这不起作用,调试仍在工作,console 调试输出给了我这个,而 Form 实际上是关闭的:

The thread 0x65c has exited with code 0 (0x0).
The thread 0x11c0 has exited with code 0 (0x0).

知道如何用 [X] 按钮完全停止这种情况吗?

【问题讨论】:

  • 我没有真正理解你的意思,因为这个应用程序需要在用户需要时启动,就像记事本一样。但是当 Thread 运行 Application.Run 时。应用程序在关闭后仍然可以在没有表单的情况下运行。我试图用 Form_Closing 处理这个问题,但它不起作用。唯一有效的是 Application.Exit(),但这不能用表单上的 X 按钮执行
  • TH.IsBackground = true;
  • 哦,您找到了解决方法。行。请注意Thread 对象的IsBackground 属性。总有一天你会需要它。

标签: c# forms formclosing


【解决方案1】:

好的,我设法解决了。

Form1.Designer.csInitializeComponent()

这个需要添加

this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_Closing);

然后在 Form1.cs

private void Form1_Closing(object sender, EventArgs e)
{
    Application.Exit();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多