Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"On Exit" for a Console Application [duplicate]

Tags:

c#

.net

I am looking for a way to trigger a piece of code when a console application is manually closed (users closes window). Been trying with:

AppDomain.CurrentDomain.ProcessExit +=     new EventHandler(CurrentDomain_ProcessExit); 

but the above doesn't work if manually closed.

Is there any ways to use a .Net call for this or do I need to import the Kernel dll and do it that way?

like image 259
BlueVoodoo Avatar asked Jan 10 '11 12:01

BlueVoodoo


People also ask

How do I stop the console window from closing in C++?

Before the end of your code, insert this line: system("pause"); This will keep the console until you hit a key.

Why does my C++ program close automatically?

When the execution is completed, the program exits immediately and hence they close. To prevent this, you can type the following at the end of your main function, before the 'return 0;' line, if you are using one in your code.


2 Answers

This code works to catch the user closing the console window:

using System; using System.Runtime.InteropServices;  class Program {     static void Main(string[] args) {         handler = new ConsoleEventDelegate(ConsoleEventCallback);         SetConsoleCtrlHandler(handler, true);         Console.ReadLine();     }      static bool ConsoleEventCallback(int eventType) {         if (eventType == 2) {             Console.WriteLine("Console window closing, death imminent");         }         return false;     }     static ConsoleEventDelegate handler;   // Keeps it from getting garbage collected     // Pinvoke     private delegate bool ConsoleEventDelegate(int eventType);     [DllImport("kernel32.dll", SetLastError = true)]     private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);  } 

Beware of the restrictions. You have to respond quickly to this notification, you've got 5 seconds to complete the task. Take longer and Windows will kill your code unceremoniously. And your method is called asynchronously on a worker thread, the state of the program is entirely unpredictable so locking is likely to be required. Do make absolutely sure that an abort cannot cause trouble. For example, when saving state into a file, do make sure you save to a temporary file first and use File.Replace().

like image 100
Hans Passant Avatar answered Oct 22 '22 04:10

Hans Passant


You need to hook to console exit event and not your process.

http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx

Capture console exit C#

like image 21
Madhur Ahuja Avatar answered Oct 22 '22 04:10

Madhur Ahuja