Click here to Skip to main content
Click here to Skip to main content
Go to top

Shut Down, Restart, Log off or Lock your computer in C#

, 19 Oct 2012
Rate this:
Please Sign up or sign in to vote.
A tip about how to shut down, restart, log off or lock 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(); 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

ProgramFOX

Belgium Belgium
No Biography provided

Comments and Discussions

 
Question+5 vote PinprofessionalMeher Khan9-Aug-14 23:20 
AnswerRe: +5 vote PinmvpProgramFOX16-Aug-14 23:32 
GeneralMy vote of 5 PinmemberGun Gun Febrianza23-Oct-12 21:27 
QuestionHello PinmemberGun Gun Febrianza23-Oct-12 21:26 
AnswerRe: Hello [modified] PinmemberProgramFOX24-Oct-12 2:05 
GeneralRe: Hello PinmemberGun Gun Febrianza24-Oct-12 5:18 
GeneralRe: Hello PinmemberProgramFOX24-Oct-12 5:21 
GeneralRe: Hello Pinmember Gun Gun Febrianza24-Oct-12 5:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 19 Oct 2012
Article Copyright 2012 by ProgramFOX
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid