I'm developing a C# console application in .Net Framework 4.6.1, Visual Studio 2013, Windows 10 x64. I want to save last runtime timestamp in the Properties.Settings.Default.LastRuntime
property settings every time when the application closes. It should work when user closes it by clicking on close [X] button, Ctrl+C
, Ctrl+Break
, windows shutdown, logoff events. Here is my code. Nothing seems to be working. LastRuntime
property is not updating:
static void Main(string[] args)
{
string lrt = Properties.Settings.Default.LastRuntime;
Console.Write(lrt);
Console.ReadLine();
handler = new ConsoleEventDelegate(ConsoleEventCallback);
SetConsoleCtrlHandler(handler, true);
}
// Handle application termination
static bool ConsoleEventCallback(int eventType)
{
// Termination events: Ctrl+C = 0, Ctrl+Break = 1, Close/Cancel = 2, Logoff = 5, Shutdown = 6
if (new[] { 0, 1, 2, 5, 6 }.Contains(eventType))
{
Properties.Settings.Default.LastRuntime = DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'hh':'mm':'ss");
Properties.Settings.Default.Save();
}
return false;
}
static ConsoleEventDelegate handler;
private delegate bool ConsoleEventDelegate(int eventType);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);