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






4.94/5 (25 votes)
A tip about how to shut down, restart, log off, lock, hibernate or sleep your computer in C#.
- Download VS 2012 project and source code without executable - 14.3 KB
- Download VS 2012 project, source code and executable - 51.3 KB
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);