You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测Windows中shutdown /t xx触发的活动关机计时器?

检测Windows定时关机状态的实现方案

一、注册表查询方法

当通过shutdown /t xx触发定时关机后,Windows会在注册表中记录倒计时状态,可通过以下路径查询:

  • 注册表路径:HKLM\SYSTEM\CurrentControlSet\Control\Shutdown
  • 关键值:Timeout(REG_DWORD类型),存储剩余关机倒计时秒数;Reason存储关机原因代码。

若Timeout值存在且大于0,说明当前有活动的关机计时器;执行shutdown /a取消后,该值会被清除或设为0。

ASP.NET中读取该值的代码示例:

using Microsoft.Win32;

public bool HasActiveShutdownTimer()
{
    try
    {
        using (var key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Shutdown"))
        {
            if (key != null)
            {
                var timeoutValue = key.GetValue("Timeout");
                if (timeoutValue is int timeout && timeout > 0)
                {
                    return true;
                }
            }
        }
    }
    catch (Exception ex)
    {
        // 处理注册表访问异常,如应用池权限不足
    }
    return false;
}

注意:需确保ASP.NET应用池身份具备读取HKLM注册表的权限,必要时调整应用池权限设置。

二、WMI 查询方法

WMI的Win32_OperatingSystem类提供ShutdownPending属性,可直接判断是否存在待执行的关机操作:

using System.Management;

public bool IsShutdownPending()
{
    try
    {
        using (var searcher = new ManagementObjectSearcher("SELECT ShutdownPending FROM Win32_OperatingSystem"))
        {
            foreach (var obj in searcher.Get())
            {
                if (obj["ShutdownPending"] is bool pending && pending)
                {
                    return true;
                }
            }
        }
    }
    catch (ManagementException ex)
    {
        // 处理WMI访问异常
    }
    return false;
}

若需获取剩余关机时间,可通过P/Invoke调用Windows APIGetSystemShutdownParameters解析:

using System.Runtime.InteropServices;

public static class ShutdownHelper
{
    [DllImport("user32.dll", SetLastError = true)]
    private static extern bool GetSystemShutdownParameters(out int puiShutdownFlags, out uint pulReason);

    public static int? GetRemainingShutdownSeconds()
    {
        int flags;
        uint reason;
        if (GetSystemShutdownParameters(out flags, out reason))
        {
            const int SHUTDOWN_GRACE_PERIOD_MASK = 0xFFFF;
            int gracePeriod = flags & SHUTDOWN_GRACE_PERIOD_MASK;
            return gracePeriod > 0 ? gracePeriod : null;
        }
        return null;
    }
}

三、补充实现细节

  • 结合注册表与WMI方法可提升检测准确性:注册表Timeout值直接对应shutdown /t的倒计时,WMIShutdownPending可覆盖所有类型的待关机状态。
  • 取消关机的ASP.NET实现:直接调用shutdown /a命令即可:
using System.Diagnostics;

public void CancelShutdown()
{
    Process.Start(new ProcessStartInfo("shutdown.exe", "/a")
    {
        CreateNoWindow = true,
        UseShellExecute = false
    });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:45:29