Capture console exit C#
I am not sure where I found the code on the web, but I found it now in one of my old projects. This will allow you to do cleanup code in your console, e.g. when it is abruptly closed or due to a shutdown...
[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);
private delegate bool EventHandler(CtrlType sig);
static EventHandler _handler;
enum CtrlType
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT = 1,
CTRL_CLOSE_EVENT = 2,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT = 6
}
private static bool Handler(CtrlType sig)
{
switch (sig)
{
case CtrlType.CTRL_C_EVENT:
case CtrlType.CTRL_LOGOFF_EVENT:
case CtrlType.CTRL_SHUTDOWN_EVENT:
case CtrlType.CTRL_CLOSE_EVENT:
default:
return false;
}
}
static void Main(string[] args)
{
// Some biolerplate to react to close window event
_handler += new EventHandler(Handler);
SetConsoleCtrlHandler(_handler, true);
...
}
Update
For those not checking the comments it seems that this particular solution does not work well (or at all) on Windows 7. The following thread talks about this
On Exit for a Console Application
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#
Gracefully (and controlled) exit from .NET console application
So the solution I found has the following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
private static bool keepRunning = true;
public static void Main(string[] args)
{
Console.WriteLine("Main started");
Console.CancelKeyPress += delegate (object sender, ConsoleCancelEventArgs e) {
e.Cancel = true;
keepRunning = false;
};
while (keepRunning)
{
Console.WriteLine("Doing really evil things...");
System.Threading.Thread.Sleep(3000);
}
Console.WriteLine("Exited gracefully");
}
}
}
Detect console exit event
Use the CancelKeyPress event (fired on CTRL+C).
Console.CancelKeyPress += Console_CancelKeyPress;
do things before close here
private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
Process.GetCurrentProcess().CloseMainWindow();
}
Hopefully this is what you tried to do.
What is the command to exit a console application in C#?
You can use Environment.Exit(0);
and Application.Exit
Environment.Exit(0)
is cleaner.
Related Topics
How to Escape Braces (Curly Brackets) in a Format String in .Net
Nullable Types and the Ternary Operator: Why Is '? 10: Null' Forbidden
Increase Upload File Size in ASP.NET Core
Does C# Support Return Type Covariance
Difference Between Const and Readonly in C#
What Is the Overhead of Creating a New Httpclient Per Call in a Webapi Client
String Was Not Recognized as a Valid Datetime " Format Dd/Mm/Yyyy"
Ef Codefirst: Should I Initialize Navigation Properties
How to Get the Index of the Current Iteration of a Foreach Loop
Transactionscope Automatically Escalating to Msdtc on Some Machines
Why Is Jsonrequestbehavior Needed
How to Convert Json to Xml or Xml to Json
Filesystemwatcher Changed Event Is Raised Twice
How to Specify a [Dllimport] Path At Runtime
How to Update the Gui from Another Thread