How to use C # code to get your computer off, restart, logoff, lock, Hibernate, sleep

Source: Internet
Author: User

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:
usingSystem.Diagnostics;
usingSystem.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:

[DllImport("user32")]
publicstatic extern bool ExitWindowsEx(uint uFlags, uintdwReason);

You can then use the following code to implement logoff:

ExitWindowsEx(0,0);
Lock

As with logoff, you also need to declare a function:

[DllImport("user32")]
publicstatic extern voidLockWorkStation();

The lock can then be implemented using the following code:

LockWorkStation();
Sleep and sleep

Again, you need to declare a function:

[DllImport("PowrProf.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
publicstatic extern bool SetSuspendState(bool hiberate, bool forceCritical, booldisableWakeEvent);

To implement hibernation, the code is as follows:

SetSuspendState(truetruetrue);

To achieve sleep, the code is as follows:

View Source code Printing Help
SetSuspendState(falsetruetrue);

How to use C # code to get your computer off, restart, logoff, lock, Hibernate, sleep

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.