WM_QUERYENDSESSION is causing me problems
Question
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.
Solution
Have you tried
[DllImport("advapi32.dll", SetLastError=true)]
static extern bool AbortSystemShutdown(string lpMachineName);
Should abort the shutdown.
OTHER TIPS
This link is relevant. It explains that you should use ShutdownBlockReasonCreate and ShutdownBlockReasonDestroy.
I got this working fine now by adding this code in
[DllImport("user32.dll", SetLastError = true)]
static extern int CancelShutdown();
I also changed the header from WM_QUERYENDSESSION = 0x11; to WM_QUERYENDSESSION = 0x0011;
Not sure if this has done anything, but the code seems to work, Thanks to all the answers