Tray app allows the system to kill my program on logout or logoff
My program starts with windows, I have code like this to prevent the application from exiting when the user presses the exit button:
protected override void OnClosing(CancelEventArgs e)
{
this.ShowInTaskbar = false;
e.Cancel = true;
this.Hide();
}
It works very well, but when I want to shut down my computer, every time I get a screen like "One or more applications cannot be closed. Cancel - exit anyway."
How can I let windows exit my application normally, but also prevent the user from exiting when the red exit button is pressed?
+3
source to share
2 answers
See How to detect a Windows shutdown or shutdown .
In your event handler, SessionEnded
set a boolean value of the type SessionEnded
and in your OnClosing test for that value:
if (!sessionEnded)
{
e.Cancel = true;
this.Hide();
}
+4
source to share
This helped (thanks to CodeCaster):
private static int WM_QUERYENDSESSION = 0x11;
private static bool systemShutdown = false;
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg == WM_QUERYENDSESSION)
{
systemShutdown = true;
}
// If this is WM_QUERYENDSESSION, the closing event should be
// raised in the base WndProc.
base.WndProc(ref m);
} //WndProc
protected override void OnClosing(CancelEventArgs e)
{
this.ShowInTaskbar = false;
if (!systemShutdown)
{
e.Cancel = true;
this.Hide();
}
}
+1
source to share