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

C#如何实现带确认提示的Windows系统重启功能?

带确认提示的Windows系统重启功能实现方案

你目前的代码是直接调用shutdown命令执行重启,shutdown本身没有内置交互式确认弹窗,需要你自己在调用重启命令前先加一层用户确认逻辑,确认用户同意后再执行重启操作即可。


WinForm/WPF桌面项目实现

直接调用系统自带的MessageBox弹窗做确认即可:

using System.Windows.Forms;
using System.Diagnostics;

// 你原有保留的StartShutDown方法
private static void StartShutDown(string param)
{
    ProcessStartInfo proc = new ProcessStartInfo();
    proc.FileName = "cmd";
    proc.WindowStyle = ProcessWindowStyle.Hidden;
    proc.Arguments = "/C shutdown " + param;
    Process.Start(proc);
}

public static void Restart()
{
    // 弹出确认提示框
    DialogResult confirmRes = MessageBox.Show("您确定要重启系统吗?", "重启确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
    if (confirmRes == DialogResult.Yes)
    {
        // 用户确认后执行5秒后重启
        StartShutDown("-r -t 5");
        MessageBox.Show("系统将在5秒后重启,如需取消可运行命令 shutdown -a", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}

控制台项目实现

通过控制台输入交互做确认:

using System.Diagnostics;

private static void StartShutDown(string param)
{
    ProcessStartInfo proc = new ProcessStartInfo();
    proc.FileName = "cmd";
    proc.WindowStyle = ProcessWindowStyle.Hidden;
    proc.Arguments = "/C shutdown " + param;
    Process.Start(proc);
}

public static void Restart()
{
    Console.WriteLine("您确定要重启系统吗?请输入Y确认,输入其他内容取消:");
    string input = Console.ReadLine()?.Trim().ToUpper();
    if (input == "Y")
    {
        Console.WriteLine("系统将在5秒后重启,如需取消可按Ctrl+C终止程序后运行 shutdown -a 命令");
        StartShutDown("-r -t 5");
    }
    else
    {
        Console.WriteLine("重启操作已取消");
    }
}

可选扩展:添加一键取消重启功能

如果要给用户提供可视化的取消重启入口,可以单独封装取消方法,调用shutdown的取消参数即可:

public static void CancelRestart()
{
    StartShutDown("-a");
    MessageBox.Show("系统重启已取消", "操作成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

注意事项

  • 调用shutdown命令需要程序具备对应系统操作权限,低权限账户运行可能执行失败,建议将程序设置为以管理员权限运行。
  • 倒计时参数-t 5的单位为秒,你可以根据需求调整倒计时时长。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 11:54:03