WM_QUERYENDSESSION is causing me problems

Creating a simple application, so when a user logs out of Windows, he, of course, disables the application. We are making a simple USB Alert application that shuts down when USB is detected when the user logs out.

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 happens when the Windows enforcement programs screen for closing is displayed, I read somewhere, if you return 0 to WM_QUERYENDSESSION, it does not display this, but it still displays this ...

Any ideas?

EDIT:

We used the code that someone answered, but we still get this screen.

The screen we want to avoid!

+6
source share
3 answers

You tried

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

Must interrupt shutdown.

+3
source

This link matters. It explains that you should use ShutdownBlockReasonCreate and ShutdownBlockReasonDestroy .

+3
source

Now I got this working by adding this code to

  [DllImport("user32.dll", SetLastError = true)] static extern int CancelShutdown(); 

I also changed the title with WM_QUERYENDSESSION = 0x11; to WM_QUERYENDSESSION = 0x0011;

Not sure if this did something, but the code seems to work thanks to all the answers

+1
source

All Articles