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");
To restart your computer, use this code:
Process.Start("shutdown",
"/r /t 0");
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);