Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Shut Down, Restart, Log off, Lock, Hibernate or Sleep Your Computer in C#

0.00/5 (No votes)
1 Dec 2014 2  
A tip about how to shut down, restart, log off, lock, hibernate or sleep your computer in C#.

Introduction

In this tip, I'll tell you how to shut down, restart, log off or lock your computer in C#.

Using the Code

First, add this using namespace statements:

using System.Diagnostics;
using System.Runtime.InteropServices; 

To shut down your computer, use this code:

Process.Start("shutdown","/s /t 0");    // starts the shutdown application 
                                        // the argument /s is to shut down the computer
                                        // the argument /t 0 is to tell the process that 
                                        // the specified operation needs to be completed 
                                        // after 0 seconds

To restart your computer, use this code:

Process.Start("shutdown", 
"/r /t 0"); // the argument /r is to restart the computer

To log off, add this extern method to your class:

[DllImport("user32")]
public static extern bool ExitWindowsEx(uint uFlags, uint dwReason);

Then, to log off, invoke the method:

ExitWindowsEx(0,0);

To lock your computer, add this extern method to your class:

 [DllImport("user32")]
 public static extern void LockWorkStation();

Then, to lock, invoke the method:

LockWorkStation(); 

To put your computer in Hibernate or Sleep, you need the same DllImport statement for them. Thanks to Virender Prajapati for suggesting to add these!

[DllImport("PowrProf.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool SetSuspendState(bool hiberate, bool forceCritical, bool disableWakeEvent);

To bring your computer into Hibernate:

SetSuspendState(true, true, true);

And to bring it into sleep:

SetSuspendState(false, true, true);

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here