You would need to track events like:
SystemEvents.PowerModeChanged Event (Microsoft.Win32) | Microsoft Docs[
^]
SystemEvents.SessionEnding Event (Microsoft.Win32) | Microsoft Docs[
^]
Example:
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)
{
MessageBox.Show("queryendsession: this is a logoff, shutdown, or reboot");
systemShutdown = true;
}
base.WndProc(ref m);
}
private void Form1_Closing(
System.Object sender,
System.ComponentModel.CancelEventArgs e)
{
if (systemShutdown)
{
systemShutdown = false;
if (DialogResult.Yes==MessageBox.Show("My application",
"Do you want to save your work before logging off?",
MessageBoxButtons.YesNo))
{
e.Cancel = true;
}
else
{
e.Cancel = false;
}
}
}