C# 实现windows 关机、重启、休眠 功能源码

首次发布:2025-12-31
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace ComputerPower.Common
{
    public class SystemShutdown
    {
        /// <summary>
        /// 关机或重启计算机
        /// </summary>
        /// <param name="action">操作类型:shutdown(关机), restart(重启), logoff(注销), hibernate(休眠), sleep(睡眠)</param>
        /// <param name="delaySeconds">延迟时间(秒),默认30秒</param>
        /// <param name="force">是否强制关闭程序</param>
        /// <param name="reason">关机原因代码</param>
        public static bool ShutdownComputer(string action = "shutdown",
                                           int delaySeconds = 10,
                                           bool force = false,
                                           string reason = "P:0:0")
        {
            try
            {
                string arguments = "";
                string operation = "";

                switch (action.ToLower())
                {
                    case "shutdown":
                        arguments = $"/s /t {delaySeconds}";
                        operation = "关机";
                        break;
                    case "restart":
                        arguments = $"/r /t {delaySeconds}";
                        operation = "重启";
                        break;
                    case "logoff":
                        arguments = "/l";
                        operation = "注销";
                        break;
                    case "hibernate":
                        arguments = "/h";
                        operation = "休眠";
                        break;
                    case "sleep":
                        // 使用 rundll32 进入睡眠
                        return SleepComputer();
                    case "abort":
                        // 取消关机
                        arguments = "/a";
                        operation = "取消关机";
                        break;
                    default:
                        throw new ArgumentException("未知的操作类型");
                }

                // 添加强制关闭参数
                if (force && action != "sleep" && action != "hibernate")
                {
                    arguments += " /f";
                }

                // 添加关机原因
                if (!string.IsNullOrEmpty(reason) && action != "abort")
                {
                    arguments += $" /c \"{reason}\"";
                }

                ProcessStartInfo psi = new ProcessStartInfo
                {
                    FileName = "shutdown.exe",
                    Arguments = arguments,
                    CreateNoWindow = true,
                    UseShellExecute = false
                };

                Process.Start(psi);

                Console.WriteLine($"{operation}命令已发送,延迟 {delaySeconds} 秒");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"执行{action}失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 立即关机
        /// </summary>
        public static bool ShutdownImmediate(bool force = true)
        {
            return ShutdownComputer("shutdown", 0, force);
        }

        /// <summary>
        /// 立即重启
        /// </summary>
        public static bool RestartImmediate(bool force = true)
        {
            return ShutdownComputer("restart", 0, force);
        }

        /// <summary>
        /// 取消关机/重启
        /// </summary>
        public static bool CancelShutdown()
        {
            return ShutdownComputer("abort", 0, false);
        }

        /// <summary>
        /// 使计算机进入睡眠状态
        /// </summary>
        public static bool SleepComputer()
        {
            try
            {
                // 使用 SetSuspendState API
                SetSuspendState(false, true, true);
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"进入睡眠失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 锁定计算机
        /// </summary>
        public static bool LockComputer()
        {
            try
            {
                Process.Start("rundll32.exe", "user32.dll,LockWorkStation");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"锁定计算机失败: {ex.Message}");
                return false;
            }
        }

        [DllImport("powrprof.dll", SetLastError = true)]
        private static extern bool SetSuspendState(bool hibernate, bool forceCritical, bool disableWakeEvent);
    }
}

本文来自 www.luofenming.com