Brief introduction
This article describes how to use C # code to get your computer off, restart, logoff, lock, Hibernate, sleep.
How to implement first, use the using statement to add the namespaces we need:
using System.Runtime.InteropServices; |
Shutdown
The code is as follows:
Process.Start( "shutdown" , "/s /t 0" ); // 参数 /s 的意思是要关闭计算机 |
// 参数 /t 0 的意思是告诉计算机 0 秒之后执行命令 |
Restart
The code is as follows:
Process.Start( "shutdown" , "/r /t 0" ); // 参数 /r 的意思是要重新启动计算机 |
Cancellation
You need to declare a Windows API function in your class using the DllImport method:
public static extern bool ExitWindowsEx( uint uFlags, uint dwReason); |
You can then use the following code to implement logoff:
Lock
As with logoff, you also need to declare a function:
public static extern void LockWorkStation(); |
The lock can then be implemented using the following code:
Sleep and sleep
Again, you need to declare a function:
[DllImport( "PowrProf.dll" , CharSet = CharSet.Auto, ExactSpelling = true )] |
public static extern bool SetSuspendState( bool hiberate, bool forceCritical, bool disableWakeEvent); |
To implement hibernation, the code is as follows:
SetSuspendState( true , true , true ); |
To achieve sleep, the code is as follows:
View Source code Printing Help
SetSuspendState( false , true , true ); |
How to use C # code to get your computer off, restart, logoff, lock, Hibernate, sleep