Is it possible to detect once Application.Exit was called or is there an win32 function to know when windows like to close your program, because of shutdown or anything. No Forms.
Asked
Active
Viewed 1,133 times
2 Answers
2
See the MSDN documentation for the WM_QUERYENDSESSION and WM_ENDSESSION messages; the parameters of the WM_ENDSESSION message will tell you if your app is exiting normally or because Windows is shutting down. You can handle these messages by overriding the WndProc method in your form, something like:
public partial class MainForm : Form
{
private const int WM_ENDSESSION = 0x0016;
private const uint ENDSESSION_CLOSEAPP = 0x1;
private const uint ENDSESSION_CRITICAL = 0x40000000;
private const uint ENDSESSION_LOGOFF = 0x80000000;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_ENDSESSION)
{
var sessionEnding = m.WParam.ToInt32() != 0;
if ((m.LParam.ToInt64() & ENDSESSION_CLOSEAPP) == ENDSESSION_CLOSEAPP)
{
// App closing
}
if ((m.LParam.ToInt64() & ENDSESSION_CRITICAL) == ENDSESSION_CRITICAL)
{
// Critical error
}
if ((m.LParam.ToInt64() & ENDSESSION_LOGOFF) == ENDSESSION_LOGOFF)
{
// User logging off
}
m.Result = IntPtr.Zero;
}
else
{
base.WndProc(ref m);
}
}
}

Ken Keenan
- 9,818
- 5
- 32
- 49
-
I know its old, but... the question said "no forms"... – Cabuxa.Mapache Feb 22 '18 at 15:03
1
How about this?
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
and then
/// <summary>
/// Method called when the process is exiting.
/// </summary>
private static void CurrentDomain_ProcessExit(object sender, EventArgs e)
{
// do something
}

RenniePet
- 11,420
- 7
- 80
- 106