Introduction
Sometimes, you need to control your system from your application software. For example, you may lock the computer, log-off, reboot, shutdown, etc.
Here I am going to discuss how these things can be done in .NET.
Note: You have to use un-managed code to perform this application.
Using the Code
You have to first add the System.Runtime.InteropServices using directive into your project.
In order to lock the system, you need to call the LockWorkStation() method which is in user32.dll.
First, you need to import user32.dll before calling.
Here is the code for importing user32.dll. Define the function as shown below:
[DllImport("user32.dll")]
public static extern void LockWorkStation();
Stand By and Hibernation
Call SetSuspendState method of Application class.
SetSuspendState method accepts 3 arguments.
The first argument power sets either standby or hibernate, the second argument if set to true, forces the OS to suspend all its applications. The third parameter, if set to true, disables wake events.
Below is the code for the application to stand by:
Application.SetSuspendState(PowerState.Suspend true, true);
For the application to Hibernate, use the following code:
Application.SetSuspendState(PowerState.Hibernate, true, true);
Log-off the Application
In order to log off, you need to first import user32.dll and define the function which you need to call to log off.
[DllImport("user32.dll")]
public static extern int ExitWindowsEx(int uFlags, int dwReason);
Call the ExitWindowsEx function with 2 arguments as 0, Use the following line to log off:
ExitWindowsEx(0, 0);
Rebooting the System
We use the same function ExitWindowsEx but now with different parameters:
ExitWindowsEx(2, 0);
Shutdown System
Call ExitWindowsEx with 1 and 0 as arguments for shutting down the system:
ExitWindowsEx(1, 0);
Points of Interest
I felt happy writing this code to control my system from my .NET application.
History
- 25th June, 2007: Initial post