在Windows窗体应用程序中退出事件?

时间:2015-02-25 01:41:54

标签: c# winforms

是的,我知道 - 以下其中一行通常会这样做:

AppDomain.CurrentDomain.ProcessExit += OnApplicationExit;
Application.ApplicationExit += OnApplicationExit;

void OnApplicationExit(object sender, EventArgs eventArgs) { ... }

但是当一个人在WinForms应用程序中不使用任何形式的 时呢?使它成为隐藏的 Windows应用程序 - 这不是一项服务。以上两个例子对我都不起作用。

这就是我启动WinForms应用程序的方式。如您所见,我没有将任何表单传递给Run方法

public static void Main()
{
    InitMyApp();
    // Here I tried to subscribe to the above shown events => didn't work.
    Application.Run();
}

1 个答案:

答案 0 :(得分:0)

Thread.GetDomain()。ProcessExit就是为此而努力的。

using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace Test
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            Thread.GetDomain ().ProcessExit += (object sender, EventArgs e) => {
                Console.WriteLine ("Foo!");
            };
            BackgroundWorker autokill = new BackgroundWorker ();
            autokill.DoWork += (object sender, DoWorkEventArgs e) => {
                Thread.Sleep (5000);
                Environment.Exit (0);
            };
            autokill.RunWorkerAsync ();
            Application.Run ();
        }
    }
}