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

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

yuyutoo 2025-03-30 22:53 4 浏览 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我是参考如下链接的:

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

相关推荐

YAML配置文件简介及使用(yaml 配置)

简介YAML是"YAMLAin'taMarkupLanguage"(YAML不是一种标记语言)的缩写。相比JSON格式的方便。...

教你如何解决最常见的58种网络故障排除方法

1.故障现象:网络适配器(网卡)设置与计算机资源有冲突。分析、排除:通过调整网卡资源中的IRQ和I/O值来避开与计算机其它资源的冲突。有些情况还需要通过设置主板的跳线来调整与其它资源的冲突。2.故障现...

一分钟带你了解服务器网卡(服务器网卡怎么用)

今天小编和大家聊一下服务器的网卡。什么是网卡?简单说网卡就是计算机与局域网互连的设备。计算机主要通过网卡接入网络。网卡又称为网络适配器或网络接口卡NIC(NetworkinterfaceCard)...

linux文件之ssh配置文件的含义与作用

ssh远程登录命令是操作系统(包括linux和window系统)下常用的操作命令,可以帮助用户,远程登录服务器系统,查看,操作系统相关信息。linux系统对于ssh命令有专门保存其相关配置的目录和文件...

Cilium 官方文档翻译 - IPAM(二)Kubernetes Host模式

KubernetesHostScopeciliumIPAM的kuberneteshost-scope模式通过选项ipam:kubernetes开启,将集群IP地址分配委托给每个独立的节点,并...

域名劫持跳转,域名劫持跳转的解决办法只需5步

简单来说,域名劫持就是把原本准备访问某网站的用户,在不知不觉中,劫持到仿冒的网站上,例如用户准备访问某家知名品牌的网上商店,黑客就可以通过域名劫持的手段,把其带到假的网上商店,同时收集用户的ID信息和...

Linux基本命令(linux基本命令总结)

...

Linux 磁盘和文件系统管理(linux磁盘管理fdisk)

1检测并确认新硬盘...

windows host文件怎么恢复?局域网访问全靠这些!

windowshost文件怎么恢复?windowshost文件是常用网址域名及其相应IP地址建立一个关联文件,通过这个host文件配置域名和IP的映射关系,以提高域名解析的速度,方便局域网用户使用...

Nginx配置文件详解与优化建议(nginx 配置详解)

1、概述今天来详解一下Nginx的配置文件,以及给出一些配置建议,希望能对大家有所帮助。...

Mac电脑hosts文件锁定,如何修改hosts文件权限

有时候我们需要修改hosts文件,但是网上很多教程都行不通,使用sudo命令也不行。其实有一个很简单的方法。打开终端命令行,使用如下命令即可:sudochflags-hvnoschg/etc/...

windows电脑如何修改hosts文件?(windows 修改hosts文件)

先来简单说下电脑host的作用hosts文件的作用:hosts文件是一个用于储存计算机网络中各节点信息的计算机文件;作用是将一些常用的网址域名与其对应的IP地址建立一个关联“数据库”,当用户在浏览器中...

Vigilante恶意软件行为怪异:修改Hosts文件以阻止受害者访问盗版网站

Sophos刚刚报道了一款名叫Vigilante的恶意软件,但其行为却让许多受害者感到不解。与其它专注于偷密码、搞破坏、或勒索赎金的恶意软件不同,Vigilante会通过修改Hosts文件...

hosts文件无法修改几种现象和解决方法

第一种、hosts文件修改完不是直接保存而是弹出另存为窗口解决:1、右击hosts文件——属性——把“只读”前面勾去掉。第二种、打开hosts文件时提示“你没有权限打开该文件,请向文件的所有者或管理员...

hosts文件位置在哪里,教你hosts文件位置在哪里

Hosts是一个没有扩展名的系统文件,其基本作用就是将一些常用的网址域名与其对应的IP地址建立一个关联"数据库",当用户在浏览器中输入一个需要登录的网址时,系统会首先自动从Hosts文件中寻找对应的I...

取消回复欢迎 发表评论: