views:

58

answers:

5

Shutting down a pc in vb.net is easy:

Process.Start("shutdown", "-s -t 00")

unless the user has locked the pc in which case the above fails.

How do I get around this in vb.net? How do I shutdown a locked PC?

The program will be running locally.

A: 

Have a look at this article on CodeProject which illustrates forcing a computer to shutdown remotely to give you an idea on how to do it.

tommieb75
that just calls shutdown but remotely?
njparton
+1  A: 

You could P/Invoke ExitWindowsEx

There is an example in C# there, but I'm sure you can convert it.

Preet Sangha
Wow, there must be a simpler way surely!
njparton
It's pretty simple - adjust the process level token, and then call exit windows. All it does is give the program the right to shut down. you can give that to the process dynamically. The example is a neat little class you can use.
Preet Sangha
+1  A: 

I think you're looking for the '-f' flag to force a shutdown.

Quote from a MS KB article: When the computer is locked, you can shut down the computer, if you run the Shutdown.exe command together with the -f option.

ho1
The -f flag is definitely not the way to go as it's designed to force all programs to close ungracefully so on reboot there's likely to be problems. For example on my PC it causes issues withe MS Security Essentials service on reboot.
njparton
A: 

Using the System.Management namespace is more elegant than starting an external tool. Here is a code example in C#, which should be fairly easy to convert:

http://www.dreamincode.net/forums/topic/33948-how-to-shut-down-your-computer-in-c%23/

Heinzi
Thanks for the pointer to System.Management. Found this link which helps: http://bytes.com/topic/visual-basic-net/answers/356576-how-shut-down-computer-using-vb-net
njparton
+1  A: 

For posterity:

Dim ms As ManagementScope = New ManagementScope("\\LocalHost")
    ms.Options.EnablePrivileges = True

    Dim oq As ObjectQuery = New ObjectQuery("SELECT * FROM Win32_OperatingSystem")
    Dim query1 As ManagementObjectSearcher = New ManagementObjectSearcher(ms, oq)
    Dim queryCollection1 As ManagementObjectCollection = query1.Get()

    For Each mo As ManagementObject In queryCollection1
        Dim ss As String() = {"5"}
        mo.InvokeMethod("Win32Shutdown", ss)
    Next

Google "Win32Shutdown" for more details of the flags available (ss above). 5 is a forced shutdown for when the pc is locked but it's more graceful than shutdown /f and doesn't appear to cause any problems with programs or services on restart.

njparton
+1 for sharing your solution.
Heinzi
PS: Please mark this as "accepted solution" (using the check mark next to your answer), so that this question no longer shows up as "unanswered".
Heinzi