User Tools

Site Tools

note:prog:csharp:250226:001:index

C#: Shut Down, Restart, Log off, Lock, Hibernate or Sleep Your Computer in C# (2025-02-26)

Local Backup

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);

TAGS

  • 6 person(s) visited this page until now.

Permalink note/prog/csharp/250226/001/index.txt · Last modified: 2025/02/26 08:29 by jethro

oeffentlich