Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WM_QUERYENDSESSION is causing me problems

Tags:

c#

wndproc

Making a simple application, so when the user logs out of Windows, it of course shuts the application down. We are making a simple USB Alert application which STOPS shutdown if a USB is detected when the user is logging off

This is the code so far.

public Form1()
    {
        InitializeComponent();
    }

    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;
            m.Result = (IntPtr)0;
        }

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

    } //WndProc 

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (systemShutdown)
        {
            systemShutdown = false;
            bool hasUSB = false;

            foreach (DriveInfo Drive in DriveInfo.GetDrives())
            {
                if (Drive.DriveType == DriveType.Removable)
                {
                    hasUSB = true;
                }
            }

            if (hasUSB)
            {
                e.Cancel = true;
                MessageBox.Show("You still have USB device plugged in, please unplug it and log off again");
            }
            else
            {
                e.Cancel = false;
            }
        }
    }

What is happening is that the Windows Force Programs to Quit screen is being displayed, I read somewhere if you return 0 to WM_QUERYENDSESSION it does not display this, but it is still displaying this...

Any ideas?

EDIT:

We used the code that someone responded with, but we are still getting this screen.

The screen we want to avoid!

like image 250
x06265616e Avatar asked Jun 28 '12 10:06

x06265616e


1 Answers

Have you tried

[DllImport("advapi32.dll", SetLastError=true)]
static extern bool AbortSystemShutdown(string lpMachineName);

Should abort the shutdown.

like image 199
BugFinder Avatar answered Sep 23 '22 06:09

BugFinder