如何在使用Start.Process()时关闭子命令窗口

本文关键字:窗口 命令 Process Start | 更新日期: 2023-09-27 18:10:58

我希望触发子命令窗口的关闭事件一旦它的命令完成。记住,它是从控制台应用程序启动的后台进程,所以它永远不可见。可见的是控制台应用程序。

我尝试使用退出事件,但没有工作。我试着依靠CMD来知道何时通过使用/c,/k和退出来关闭它。两者似乎都不起作用。我还尝试了一个do while循环检查HasExited,除非我在应用程序控制台窗口内键入"exit",否则这些都不起作用。它不会关闭,但会触发不可见的子命令窗口关闭。

是否有其他方法关闭它一旦子命令完成?

String msg = "echo %time%; exit;";  
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = msg;
p.EnableRaisingEvents = true;
p.Exited += p_Exited; 
p.Start();
msg += p.StandardOutput.ReadToEnd();

非常感谢!

如何在使用Start.Process()时关闭子命令窗口

我稍微修改了您的程序以运行子命令处理器,捕获其输出,然后将其写入控制台。

        char quote = '"';
        string msg = "/C " + quote + "echo %time%" + quote;
        System.Diagnostics.Process p = new System.Diagnostics.Process();
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.Arguments = msg;
        p.EnableRaisingEvents = true;
        p.Exited += (_, __) => Console.WriteLine("Exited!");
        p.Start();
        string msg1 = p.StandardOutput.ReadToEnd();
        Console.WriteLine(msg1);
下面是一个完整的程序,语法略有不同,但在精神上是相似的:
using System;
using System.Diagnostics;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            char quote = '"';
            var startInfo = new ProcessStartInfo("cmd", "/C " + quote + "echo %time%" + quote)
            { UseShellExecute = false, RedirectStandardOutput = true };
            var process = new Process { EnableRaisingEvents = true };
            process.StartInfo = startInfo;
            process.Exited += (_, __) => Console.WriteLine("Exited!");
            process.Start();
            string msg1 = process.StandardOutput.ReadToEnd();
            Console.WriteLine(msg1);
            Console.ReadLine();
        }
    }
}

或者,正如这个答案所说明的,也许就叫DateTimeOffset.Now。如果你对亚秒级信息感兴趣,可以使用Stopwatch类。

如果你喜欢用c#中的命令驱动命令行,这也是可能的。Igor Ostrovsky描述了如何将事件转换为任务;然后使用async/await创建一个看起来像过程的命令和响应序列。