Search code examples
c#.netwinformswinapiwndproc

How can I determine if the system is shutting down/restarting or if the user logged off from a WinForms app?


How can know what action user have performed ie a shutdown ,restart,stand by, lock or log off. I have used the below code to check it but i want to identify each of the case and perform a action accordingly.please suggest some method to know these details in windows form application

 private static int WM_QUERYENDSESSION = 0x11;
    protected override void WndProc(ref System.Windows.Forms.Message m)
    {
        if (m.Msg == WM_QUERYENDSESSION)
        {
            MessageBox.Show(m.Msg.ToString() + " Endsession: this is a logoff, shutdown, or reboot");
            systemShutdown = true;
        }
        // If this is WM_QUERYENDSESSION, the closing event should be
        // raised in the base WndProc.
        base.WndProc(ref m);
    }

Solution

  • You need to check the lParam value of the WM_QUERYENDSESSION message.

    As the documentation indicates:

    • If the parameter is 0, the system is shutting down or restarting (it is not possible to determine which event is occurring).

    • If the parameter is ENDSESSION_CLOSEAPP (0x00000001), the application is using a file that must be replaced, the system is being serviced, or system resources are exhausted.

    • If the parameter is ENDSESSION_CRITICAL (0x40000000), the application is forced to shut down.

    • If the parameter is ENDSESSION_LOGOFF (0x80000000), then the user is logging off.