1
votes

I am following these sample codes on MSDN to prevent windows 7 from shutdown until user confirm:

    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;
        }

        // If this is WM_QUERYENDSESSION, the closing event should be
        // raised in the base WndProc.
        base.WndProc(ref m);

    } //WndProc 

    private void Form1_FormClosing(System.Object sender, System.ComponentModel.CancelEventArgs e)
    {
        if (systemShutdown)
        // Reset the variable because the user might cancel the 
        // shutdown.
        {
            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;
            }
        }
    }

But the problem I am facing is on one PC, even if "queryendsession: this is a logoff, shutdown, or reboot" is shown ( so WM_QUERYENDSESSION is received ), Windows 7 does not wait for user's confirm and shutdowns quickly. On other PCs these codes work well. So I am wondering what is happening. Thank you very much.

Btw: I tried to directly send out e.Cancel = false in Form1_FormClosing but nothing happend. System shutdowns and there was no waiting.

1
The days that programs can block a shutdown are over and done with. Showing a message box is a singular bad idea, the user can't get to it to click it. Pay attention to the e.CloseReason property in your FormClosing event handler, if the machine is shutting down then you'll have to make a guess. Few users like to lose their work.Hans Passant
Thank you to remind me to check the reason. The reason is systemshutdown, which is the same for all tested PCs. But only the one mentioned above will shutdown immediately no matter what you do with the e.Cancel.Altrouge Brunestud

1 Answers

0
votes

This is how i did it the last time i wanted to prevent windows from shutdown:

Public Form1()
{
    InitializeComponent();

    SystemEvents.SessionEnding += SessionEndingEvtHandler;          
}

private void SessionEndingEvtHandler(object sender, SessionEndingEventArgs e)
{
    e.Cancel = true;
}