4

我想创建一个在给定时间后使用 shutdown.exe 关闭计算机的进程。

这是我的代码:

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "shutdown.exe";
startInfo.Arguments = "–s –f –t " + seconds;
Process.Start(startInfo);

其中seconds是一个 int 局部变量,由用户决定。

当我运行我的代码时,什么也没有发生。但是当我手动进入 cmd 提示符并键入:
shutdown.exe -s -f -t 999
然后 Windows 会弹出一个窗口并告诉我系统将在 16 分钟内关闭。

我认为这是由于多个参数的原因,是我中止正在进行的系统关闭的方法有效(我从 cmd 提示符手动创建了 systemshutdown)。这几乎是一样的,除了startInfo.Argument

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "shutdown.exe";
startInfo.Arguments = "-a";
Process.Start(startInfo);
4

1 回答 1

8

对shutdown.exe 的使用消息的快速检查表明,它需要斜杠('/')而不是破折号('-')之后的选项参数。

更换线路:

        startInfo.Arguments = "–s –f –t " + seconds;

和:

        startInfo.Arguments = "/s /f /t " + seconds;

使用 C# express 2010 在我的盒子上产生工作结果。

此外,您可以将标准错误和标准重定向到已启动的进程之外,以供您的程序读取,这样您就可以知道它运行后发生了什么。为此,您可以存储 Process 对象并等待底层进程退出,以便检查一切是否顺利。

        startInfo.RedirectStandardOutput = true;
        startInfo.RedirectStandardError = true;

        Process p = Process.Start(startInfo);
        string outstring = p.StandardOutput.ReadToEnd();
        string errstring = p.StandardError.ReadToEnd();
        p.WaitForExit();

不幸的是,我无法告诉您为什么命令行版本接受选项上的“破折号”前缀而 C# 执行版本不接受。但是,希望您所追求的是一个可行的解决方案。

完整的代码清单如下:

        int seconds = 100;
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.CreateNoWindow = false;
        startInfo.UseShellExecute = false;
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.FileName = "shutdown.exe";
        startInfo.Arguments = "/s /f /t " + seconds;
        startInfo.RedirectStandardOutput = true;
        startInfo.RedirectStandardError = true;
        Process p = Process.Start(startInfo);
        string outstring = p.StandardOutput.ReadToEnd();
        string errstring = p.StandardError.ReadToEnd();
        p.WaitForExit();
于 2012-01-18T18:31:22.833 回答