Resolved Shut down the computer when system is locked

JuggaloBrotha

VB.NET Forum Moderator
Staff member
Joined
Jun 3, 2004
Messages
4,530
Location
Lansing, MI; USA
Programming Experience
10+
I've noticed that a few download management programs do this, like uTorrent for example, where you can set it to shut down the system when the download(s) complete and I would like to implement this in my app as well.

Right now I'm using
VB.NET:
Process.Start("shutdown.exe", "-s -t 05")
which works fine if the user is logged in, but my home computer has the screen saver set to lock the computer in which all my app does is exit but the system doesn't shut down like it does when it's logged in. In uTorrent the system shuts down whether the user is logged in or the system is locked, how is that possible?

Also I would like to know how to detect if the system is locked or not because if they are logged in I, like uTorrent, would like to prompt the user that the system is about to shut down and give them 30 seconds to cancel it.

In addition to
VB.NET:
Process.Start("shutdown.exe", "-s -t 05")
I also know about
VB.NET:
    <DllImport("user32.dll")> _
    Public Shared Function ExitWindowsEx(ByVal uFlags As Integer, ByVal dwReason As Integer) As Integer
    End Function

    Call ExitWindowsEx(1I, 0I) 'Shut Down
but this doesn't shut down the system if it's locked either.
 
The code in the article is a little dated so I read the "forum" thing at the bottom and I got the Locked/UnLocked detection working like so:
VB.NET:
Private m_WorkStationLocked As Boolean = False

Private Sub ShutDownForm_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    RemoveHandler Microsoft.Win32.SystemEvents.SessionSwitch, AddressOf SessionSwitch
End Sub

Private Sub ShutDownForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    AddHandler Microsoft.Win32.SystemEvents.SessionSwitch, AddressOf SessionSwitch
End Sub

Private Sub SessionSwitch(ByVal sender As Object, ByVal e As Microsoft.Win32.SessionSwitchEventArgs)
    Select Case e.Reason
        Case Microsoft.Win32.SessionSwitchReason.SessionLock
            ' Computer locked
            m_WorkStationLocked = True
        Case Microsoft.Win32.SessionSwitchReason.SessionUnlock
            ' Computer unlocked
            m_WorkStationLocked = False
    End Select
End Sub
Now that it's able to know when the workstation's locked or not, it's a matter of shutting down the PC when it is locked that I have left to go.
 
Back
Top