c# - 具有多个参数的 Shutdown.exe 进程,不工作

标签 c# winforms process shutdown processstartinfo

我想创建一个使用 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 提示符下手动创建了系统关闭)。这几乎是相同的,除了 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);

最佳答案

快速检查 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# 执行版本不接受。但是,希望您所追求的是一个可行的解决方案。

完整的代码 list 如下:

        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();

关于c# - 具有多个参数的 Shutdown.exe 进程,不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8915165/

相关文章:

c# - Dictionary.ContainsKey/Value 和检查某个键/值的 foreach 循环之间的速度是否存在差异

c# - LINQ - GroupBy 和项目到新类型?

c# - 将文本框文本保存到 XML 文件中

c# - 如何在无效登录后再次显示登录表单?

c++ - fork 与父子通信

node.js - Node.js 中子进程和异步编程的概念在某种程度上是相同的吗?

c# - async 和 await 在哪里结束?困惑

c# - 是否可以在 datagridview 中切换行和列?

c# - 使用 WinForms GeckoFX 控件从 C# 调用 javascript 函数的推荐方法是什么?

c# - 如何将隐藏的输入传递给 C# 中的另一个程序