Erik Hrast
Erik Hrast

Reputation: 11

VB.Net Pausing Windows Shutdown or Logoff

I tried this to show some MsgBox when shutdown or logoff is detected.. like "You're logging off.. .

    Public Class frmDetectEnd
Private Sub frmDetectEnd_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    AddHandler Microsoft.Win32.SystemEvents.SessionEnding, AddressOf Handler_SessionEnding
End Sub

Public Sub Handler_SessionEnding(ByVal sender As Object, ByVal e As Microsoft.Win32.SessionEndingEventArgs)
    If e.Reason = Microsoft.Win32.SessionEndReasons.Logoff Then
        MessageBox.Show("User is logging off")
    ElseIf e.Reason = Microsoft.Win32.SessionEndReasons.SystemShutdown Then
        MessageBox.Show("System is shutting down")
    End If
End Sub
End Class

This detection work's OK but I want to stop shutdown/logoff process if MsgBox is shown, because at this point the shutdown/logoff process is executed and it stops with Windows message "This program is preventing to log you off...".

However, I would like that after getting message "User is logging of/System is shutting down" the user can select command button to proces something and then Shutdown or LogOff can continue.

Upvotes: 1

Views: 920

Answers (2)

J. Scott Elblein
J. Scott Elblein

Reputation: 4253

You could immediately call shutdown /a when a shutdown is detected. (/a stands for "abort").

That's a built-in command-line utility in Windows, so you'd call it the usual way of calling command-line utilities within a vb app. The trick is it has to happen fast enough.

Another more hacky way you could try would be to send a CTRL+ALT+DEL and then the Task Manager (and then hide it. Maybe you can do it all so fast the user would only see a quick flash). That usually aborts a shutdown when I've manually done it.

Upvotes: 0

Visual Vincent
Visual Vincent

Reputation: 18310

It's pretty much impossible to cancel a shutdown/logoff after it has started. At most you can get the "This program is preventing Windows from shutting down" message, like you said in your question.

A potential solution would be to create system-wide hooks for the InitiateShutdown, InitiateSystemShutdown and InitiateSystemShutdownEx functions (requires C++ or some other kind of low-level language). However, they would need to be coded carefully and tested thoroughly, and even if you managed to get them working most of the times, there's no guarantee that the OS isn't bypassing them via some other, even deeper functions (it contains a lot of both undocumented and name-mangled functions).

Source:

I researched this heavily about two years back in an attempt to make a program that would completely block system shutdown if the user chose to. However, as mentioned above, it has proven to be extremely difficult, if not impossible. None of my attempts were a success.

Upvotes: 2

Related Questions