C# Source Code: Detecting Process Exit From Console Application in C#
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Detecting Process Exit From Console Application in C#
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Thursday, March 24, 2005
Hits:
2799
Category:
General/Framework
Article:
Console applications are modeled after DOS console application where usually an application exits when Standard in completes. To handle this properly in C#, you can set a delegate to SetConsoleCtrlHandler. You will have an opportunity to clean up resource or finish your work before the application actually exits. using System.Runtime.InteropServices; // Declare the SetConsoleCtrlHandler function // as external and receiving a delegate. [DllImport("Kernel32")] public static extern bool SetConsoleCtrlHandler(HandlerRoutineDelegate Handler, bool Add); // A delegate type to be used as the handler routine // for SetConsoleCtrlHandler. public delegate bool HandlerRoutineDelegate(CtrlTypes CtrlType); // An enumerated type for the control messages // sent to the handler routine. public enum CtrlTypes { CTRL_C_EVENT = 0, CTRL_BREAK_EVENT = 1, CTRL_CLOSE_EVENT = 2, CTRL_LOGOFF_EVENT = 5, CTRL_SHUTDOWN_EVENT = 6 } // Code to handle console events private static bool ConsoleCtrlCheck(CtrlTypes ctrlType) { // Add you handler here return true; } // Example calling code // IMPORTANT - Keep a reference to the delegate to prevent GC private static HandlerRoutineDelegate handlerRoutineRef = new HandlerRoutineDelegate(ConsoleCtrlCheck); // Call API SetConsoleCtrlHandler(handlerRoutineRef, true);
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet