Sunday, December 8, 2013

To shut down, restart, log off or lock your computer in C#.

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

No comments:

Post a Comment