You need to enable JavaScript to run this app. 如何使用C#强制Windows系统从待机模式唤醒
优惠活动
大模型
产品
解决方案
定价
更多

如何使用C#强制Windows系统从待机模式唤醒

C#实现Windows待机状态强制唤醒方案

实现前提

  • 程序必须以管理员权限运行,否则无法调用系统电源相关的特权API
  • 若需通过外接设备触发唤醒,需先进入设备管理器对应设备的「电源管理」标签页,勾选「允许此设备唤醒计算机」;可运行命令powercfg /devicequery wake_armed确认已配置的可唤醒设备列表

核心实现逻辑

Windows内核提供了可等待定时器API,支持配置定时器触发时唤醒处于睡眠/待机状态的系统,C#可通过P/Invoke调用这组API实现需求:

  1. 调用CreateWaitableTimer创建支持唤醒的可等待定时器
  2. 调用SetWaitableTimer设置定时器触发时间,配置唤醒标识
  3. 等待定时器触发即可自动唤醒系统,若要配合外接设备触发,可在接收到设备的触发信号时调用相关逻辑设置立即触发的定时器

代码示例

using System;
using System.Runtime.InteropServices;

public class SystemWakeHelper
{
    // 导入Windows API
    [DllImport("kernel32.dll")]
    private static extern IntPtr CreateWaitableTimer(IntPtr lpTimerAttributes, bool bManualReset, string lpTimerName);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool SetWaitableTimer(IntPtr hTimer, [In] ref long pDueTime, int lPeriod, IntPtr pfnCompletionRoutine, IntPtr lpArgToCompletionRoutine, bool fResume);

    [DllImport("kernel32.dll")]
    private static extern bool CloseHandle(IntPtr hObject);

    /// <summary>
    /// 设置系统唤醒时间
    /// </summary>
    /// <param name="delaySeconds">距离现在多少秒后唤醒系统,填0则立即触发唤醒</param>
    /// <returns>设置是否成功</returns>
    public static bool SetSystemWake(int delaySeconds)
    {
        // 时间单位为100纳秒,负值表示相对当前时间的偏移
        long duetime = -1 * delaySeconds * 10000000; 
        IntPtr timerHandle = CreateWaitableTimer(IntPtr.Zero, false, null);
        if (timerHandle == IntPtr.Zero) return false;
        
        // SetWaitableTimer最后一个参数fResume设为true即表示触发时唤醒系统
        bool success = SetWaitableTimer(timerHandle, ref duetime, 0, IntPtr.Zero, IntPtr.Zero, true);
        CloseHandle(timerHandle);
        return success;
    }

    // 调用示例:接收到外接设备触发信号时调用SetSystemWake(0)即可立即唤醒待机系统
}

注意事项

  • 若系统处于休眠(S4)状态而非待机(S3),需确保BIOS中开启了休眠唤醒支持,否则上述方案不生效
  • 部分笔记本默认限制了除电源键外的设备唤醒权限,可运行powercfg /a查看系统支持的所有唤醒状态

内容的提问来源于stack exchange,提问作者Jonathan Perennes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 20:12:02