我希望在命令完成后触发子命令窗口的关闭事件。请记住,这是从控制台应用程序启动的后台进程,因此它永远都不可见。可见的是控制台应用程序。
我尝试使用Exited事件,但是没有用。我尝试依靠CMD来了解何时使用/ c,/ k和退出将其关闭。似乎都不起作用。我还尝试了一个做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();
非常感谢你!!
我稍微修改了程序以运行子命令处理器,捕获其输出,然后将其写入控制台。
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
class。
如果您更愿意使用C#中的命令来驱动命令行,则也可以。伊戈尔·奥斯特洛夫斯基(Igor Ostrovsky)介绍了如何将事件转换为任务。然后使用async / await创建一个看起来像过程的命令和响应序列。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句