百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程文章 > 正文

C# 控制电脑睡眠,休眠,关机以及唤醒

qiyuwang 2025-03-20 18:33 11 浏览 0 评论

最近碰到一个关于芯片测试过程中的问题,这颗芯片是用在笔记本端口上,笔记本客户那边会有一个压力测试,就是频繁的电脑电源状态切换,S0(正常使用的开机状态),S3(睡眠模式),S4(休眠模式)以及S5(关机模式)。

当然,主要是客户在压力测试过程中,发现了芯片会不正常的死锁,客户那边将机台寄回来,那么该如何复现呢?客户那边会有自己的一套压力测试系统,不过会测试很多东西,不太方便给我们,而且每一次循环耗时比较久。那么,能不能自己搭建一套控制电脑睡眠,休眠,关机以及唤醒的程序呢?

上面讲的是一个应用背景,告诉大家这其实也是有需求的,只是平时不太用而已,将其记录下来:

首先,从电脑开机状态S0切换到S3,S4甚至是S5,都是比较容易实现的,见下面代码:

Application.SetSuspendState(PowerState.Suspend, false, false);//从S0进入S3
Application.SetSuspendState(PowerState.Hibernate,false,false);//从S0进入S4

Process.Start("shutdown","/s /t 0");    // 参数 /s 的意思是要关闭计算机
                                        // 参数 /t 0 的意思是告诉计算机 0 秒之后执行命令
Process.Start("shutdown", "/r /t 0"); // 参数 /r 的意思是要重新启动计算机

只要调用上述语句即可实现从S0到其他的电源状态,那么反过来唤醒呢?

唤醒的难点在于:当处于S3,S4以及S5的状态下,我的上位机程序是不会运行的,因此,在上位机软件的定时唤醒也是没法工作的。那么笔记本客户那边是怎么操作的呢?他们会通过底层的EC控制来显示上述的功能,可是,我们是不知道底层EC的接口,而且,我们需要一个通用的程式,那要怎么实现呢?

在笔记本的设计中,在S3,S4,S5通常不是所有的东西都会关掉,通常会有一个硬件定时器还在开着,如果我们能操作这个定时器,那是不是就可以实现我们想要的功能呢?

可以调用下面的两个函数,即CreateWaitableTimer以及SetWaitableTimer,这两个函数就可以控制电脑里面开的硬件定时器,当然这个硬件定时器是CPU里面的还是EC里面的,我也不太清楚,没研究过,如果有大神研究过,可以留言,我也学习学习。

[DllImport("kernel32.dll")]
public static extern SafeWaitHandle CreateWaitableTimer(IntPtr lpTimerAttributes, bool bManualReset, string lpTimerName);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWaitableTimer(SafeWaitHandle hTimer, [In] ref long pDueTime, int lPeriod, IntPtr pfnCompletionRoutine, IntPtr lpArgToCompletionRoutine, bool fResume);

另外,需要说明的一点是,使用这个定时器也是有条件的,你需要先设置笔记本,"Control Panel > Power Options > Change Plan Settings > Change Advanced Power Settings > Sleep > Allow Wake Timers", 使能定时器唤醒,还有就是,"Control Panel > Power Options > Change Plan Settings > Change Advanced Power Settings > Brad / Additional Settings > Require a password on wakeup",关闭唤醒需要密码。

完成上面的设置,其实已经可以实现电脑从S3,S4,S5唤醒了,但在我使用的过程中,其实还碰到了一个问题,就是唤醒之后,屏幕不亮,你就会误认为没有唤醒,因此我增加了控制鼠标移动的命令,这样,唤醒之后,屏幕就会亮起。

[DllImport("user32.dll")]
public static extern void mouse_event(Int32 dwFlags, Int32 dx, Int32 dy, Int32 dwData, UIntPtr dwExtraInfo);

mouse_event(0x0001,0,1,0,UIntPtr.Zero);
mouse_event(0x0001, 0, -1, 0, UIntPtr.Zero);

另外还有一点需要注意,就是笔记本从S0->S3/S4/S5->S0这个循环里面,S0,S3/S4/S5这几个状态的停留时间一定要足够,因为,每个笔记本的完全进入各个状态的时间会不一样,比如,我用我自己的笔记本,这几个状态的停留时间要至少20s,否则,笔记本还没有完全进入就要退出,就会导致,电脑把WaitableTimer关掉,而笔记本还没有唤醒,导致程式死锁。而新的刚买的笔记本,只需要设置10s即可完全进入。

废话不多说,直接上代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;

namespace AutoSwitchGUI
{
    public partial class AutoSwitchGUI : Form
    {
        [DllImport("kernel32.dll")]
        public static extern SafeWaitHandle CreateWaitableTimer(IntPtr lpTimerAttributes, bool bManualReset, string lpTimerName);

        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetWaitableTimer(SafeWaitHandle hTimer, [In] ref long pDueTime, int lPeriod, IntPtr pfnCompletionRoutine, IntPtr lpArgToCompletionRoutine, bool fResume);

        [DllImport("kernel32.dll")]
        public static extern uint SetThreadExecutionState(uint esFlags);

        [DllImport("user32.dll")]
        public static extern void mouse_event(Int32 dwFlags, Int32 dx, Int32 dy, Int32 dwData, UIntPtr dwExtraInfo);

        //public event EventHandler Woken;
        private BackgroundWorker bgWorker = new BackgroundWorker();

        public struct auto_switch_gui_status_t
        {
            public bool test_status;
            public UInt64 test_times_cnt;
            public UInt64 test_times;
            public byte cur_state;

            public int s0_duration;
            public int s3_duration;
        }
        public auto_switch_gui_status_t auto_switch_status;
        public AutoSwitchGUI()
        {
            InitializeComponent();
            bgWorker.DoWork += new DoWorkEventHandler(bgWorker_Dowork);
            bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
        }

        private void bgWorker_Dowork(object sender, DoWorkEventArgs e)
        {
            long waketime = (long)e.Argument;
            using (SafeWaitHandle handle = CreateWaitableTimer(IntPtr.Zero, true, this.GetType().Assembly.GetName().Name.ToString() + "Timer"))
            {
                if (SetWaitableTimer(handle, ref waketime, 0, IntPtr.Zero, IntPtr.Zero, true))
                {
                    using (EventWaitHandle wh = new EventWaitHandle(false, EventResetMode.AutoReset))
                    {
                        wh.SafeWaitHandle = handle;
                        wh.WaitOne();
                    }
                }
                else
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
        }

        private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            mouse_event(0x0001,0,1,0,UIntPtr.Zero);
            mouse_event(0x0001, 0, -1, 0, UIntPtr.Zero);
            auto_switch_status.test_times_cnt++;
            TestTimes.Text = auto_switch_status.test_times_cnt.ToString();
            SystemTimer.Interval = auto_switch_status.s0_duration * 1000;
            SystemTimer.Start();
        }

        public void SetWakeUpTime(UInt64 time)
        {
            bgWorker.RunWorkerAsync(System.DateTime.Now.AddSeconds(time).ToFileTime());
        }

        private void StartButton_Click(object sender, EventArgs e)
        {
            try
            {
                auto_switch_status.test_times = UInt64.Parse(SetTestTimes.Text);
                auto_switch_status.s0_duration = int.Parse(S0Duration.Text);
                auto_switch_status.s3_duration = int.Parse(S3Duration.Text);
                if (auto_switch_status.test_times > 0)
                {
                    //SetThreadExecutionState(0x00000001 | 0x00000002 | 0x80000000 | 0x00000040);
                    TestStatus.BackColor = Color.Green;
                    auto_switch_status.test_status = true;
                    TestTimes.Text = "0";
                    auto_switch_status.test_times_cnt = 0;
                    SystemTimer.Interval = auto_switch_status.s0_duration*1000;
                    auto_switch_status.cur_state = 0;
                    SystemTimer.Start();
                    return;
                }
            }
            catch
            {

            }
            MessageBox.Show("Configuration Failed!");
        }

        private void StopButton_Click(object sender, EventArgs e)
        {
            SystemTimer.Stop();
            auto_switch_status.test_status = true;
            TestStatus.BackColor = Color.Red;
        }

        private void SystemTimer_Tick(object sender, EventArgs e)
        {
            if (auto_switch_status.cur_state == 0)
            {
                auto_switch_status.cur_state = 0;
                SystemTimer.Stop();
                if (auto_switch_status.test_times_cnt >= auto_switch_status.test_times)
                {
                }
                else
                {
                    SetWakeUpTime((UInt64)auto_switch_status.s3_duration);
                    Application.SetSuspendState(PowerState.Suspend, false, false);
                    //Application.SetSuspendState(PowerState.Hibernate, false, false);
                }
                

            }
            else if (auto_switch_status.cur_state == 1)
            {
                auto_switch_status.test_times_cnt++;
                TestTimes.Text = auto_switch_status.test_times_cnt.ToString();
                auto_switch_status.cur_state = 0;
                
                SendKeys.Send(" ");
                MessageInfo.Text += "TEST1\r\n";
            }
        }
    }
}

另外声明,关于SetWaitableTimer和CreateWaitableTimer我是参考如下链接的:

希望可以帮到大家,上面代码在我自己的笔记本以及客户的笔记本是可以适用的。

相关推荐

# 安装打开 ubuntu-22.04.3-LTS 报错 解决方案

#安装打开ubuntu-22.04.3-LTS报错解决方案WslRegisterDistributionfailedwitherror:0x800701bcError:0x80070...

利用阿里云镜像在ubuntu上安装Docker

简介:...

如何将Ubuntu Kylin(优麒麟)19.10系统升级到20.04版本

UbuntuKylin系统使用一段时间后,有新的版本发布,如何将现有的UbuntuKylin系统升级到最新版本?可以通过下面的方法进行升级。1.先查看相关的UbuntuKylin系统版本情况。使...

Ubuntu 16.10内部代号确认为Yakkety Yak

在正式宣布Ubuntu16.04LTS(XenialXerus)的当天,Canonical创始人MarkShuttleworth还非常开心的在个人微博上宣布Ubuntu下个版本16.10的内...

如何在win11的wsl上装ubuntu(怎么在windows上安装ubuntu)

在Windows11的WSL(WindowsSubsystemforLinux)上安装Ubuntu非常简单。以下是详细的步骤:---...

Win11学院:如何在Windows 11上使用WSL安装Ubuntu

IT之家2月18日消息,科技媒体pureinfotech昨日(2月17日)发布博文,介绍了3中简便的方法,让你轻松在Windows11系统中,使用WindowsSubs...

如何查看Linux的IP地址(如何查看Linux的ip地址)

本头条号每天坚持更新原创干货技术文章,欢迎关注本头条号"Linux学习教程",公众号名称“Linux入门学习教程"。...

怎么看电脑系统?(怎么看电脑系统配置)

要查看电脑的操作系统信息,可以按照以下步骤操作,根据不同的操作系统选择对应的方法:一、Windows系统通过系统属性查看右键点击桌面上的“此电脑”(或“我的电脑”)图标,选择“属性”。在打开的...

如何查询 Linux 内核版本?这些命令一定要会!

Linux内核是操作系统的核心,负责管理硬件资源、调度进程、处理系统调用等关键任务。不同的内核版本可能支持不同的硬件特性、提供新的功能,或者修复了已知的安全漏洞。以下是查询内核版本的几个常见场景:...

深度剖析:Linux下查看系统版本与CPU架构

在Linux系统管理、维护以及软件部署的过程中,精准掌握系统版本和CPU架构是极为关键的基础操作。这些信息不仅有助于我们深入了解系统特性、判断软件兼容性,还能为后续的软件安装、性能优化提供重要依据。接...

504 错误代码解析与应对策略(504错误咋解决)

在互联网的使用过程中,用户偶尔会遭遇各种错误提示,其中504错误代码是较为常见的一种。504错误并非意味着网站被屏蔽,它实际上是指服务器在规定时间内未能从上游服务器获取响应,专业术语称为“Ga...

猎聘APP和官网崩了?回应:正对部分职位整改,临时域名可登录

10月12日,有网友反映猎聘网无法打开,猎聘APP无法登录。截至10月14日,仍有网友不断向猎聘官方微博下反映该情况,而猎聘官方微博未发布相关情况说明,只是在微博内对反映该情况的用户进行回复,“抱歉,...

域名解析的原理是什么?域名解析的流程是怎样的?

域名解析是网站正常运行的关键因素,因此网站管理者了解域名解析的原理和流程对于做好域名管理、解决常见解析问题,保障网站的正常运转十分必要。那么域名解析的原理是什么?域名解析的流程是怎样的?接下来,中科三...

Linux无法解析域名的解决办法(linux 不能解析域名)

如果由于误操作,删除了系统原有的dhcp相关设置就无法正常解析域名。  此时,需要手动修改配置文件:  /etc/resolv.conf  将域名解析服务器手动添加到配置文件中  该文件是DNS域名解...

域名劫持是什么?(域名劫持是什么)

域名劫持是互联网攻击的一种方式,通过攻击域名解析服务器(DNS),或伪造域名解析服务器(DNS)的方法,把目标网站域名解析到错误的地址从而实现用户无法访问目标网站的目的。说的直白些,域名劫持,就是把互...

取消回复欢迎 发表评论: