0

Yeah I know - one of the following lines will do this usually:

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

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

But what when one don't use any forms in a WinForms application? To make it a hidden windows application - which is not a service. Both of the above examples don't work for me.

This is how I start my WinForms app. As you can see I don't pass any form to the Run method

public static void Main()
{
    InitMyApp();
    // Here I tried to subscribe to the above shown events => didn't work.
    Application.Run();
}
boop
  • 7,413
  • 13
  • 50
  • 94
  • 1
    `AppDomain.ProcessExit` works fine for me in a console application (i.e. no forms). Your example shows no attempt to use _either_ method. Please include [a good, _minimal_, _complete_ code example](http://stackoverflow.com/help/mcve) that clearly illustrates your question. – Peter Duniho Feb 25 '15 at 01:54
  • @PeterDuniho Well there is no way to make a hidden console application - AFAIK. That's the reason why I've asked especially for WinForms. Create a WinForms Project and remove the content of `Main()` and just do `Application.Run()` => it will run - but *hidden*. Updated my question to make things hopefully more clear – boop Feb 25 '15 at 02:08
  • These might help? http://stackoverflow.com/questions/20675024/when-will-appdomain-processexit-not-get-called and http://stackoverflow.com/questions/1157009/application-exit-even-not-firing-in-c-sharp-windows-application – Anderson Matos Feb 25 '15 at 02:22
  • 1
    I guess it depends on your definition of "hidden". That said, my point was mainly that a) the `ProcessExit` event seems to work fine regardless, and b) if you don't post code showing how _you_ are trying to use `ProcessExit`, no one can help you figure out how _to fix that code_. – Peter Duniho Feb 25 '15 at 04:58

1 Answers1

0

Thread.GetDomain().ProcessExit worked on this end.

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