c#隐藏cmd窗口需要输入

本文关键字:输入 窗口 隐藏 cmd | 更新日期: 2023-09-27 18:11:40

在我的代码中,我需要运行很多cmd命令。他们一定都藏起来了。作为示例,我将向您展示两个命令的代码。

string cmdText = @"/c regsvr32 vbscript.dll";
System.Diagnostics.Process temp = new System.Diagnostics.Process();
temp.StartInfo.Arguments = cmdText;
temp.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
temp.StartInfo.FileName = "cmd.exe";
temp.EnableRaisingEvents = true;
temp.Start();
temp.WaitForExit();
cmdText = @"/c regsvr32 jscript.dll";
temp.StartInfo.Arguments = cmdText;
temp.Start();
temp.WaitForExit();

现在的问题是一些命令(例如:gpupdate /force)需要输入(例如"Y/N")。我如何把这个输入给cmd?

c#隐藏cmd窗口需要输入

您需要读取程序的输出并处理它/将所需的输入写回进程。为了实现这一点,您还需要设置Process/ProcessStartInfo的一些属性:

string cmdText = @"/c regsvr32 vbscript.dll";
System.Diagnostics.Process temp = new System.Diagnostics.Process();
temp.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
temp.StartInfo.CreateNoWindow = true;
temp.StartInfo.Arguments = cmdText;
temp.StartInfo.FileName = "cmd.exe";
temp.StartInfo.RedirectStandardOutput=true;
temp.StartInfo.RedirectStandardInput=true;
temp.StartInfo.UseShellExecute=false;
temp.Start();
// Read program's output
StringBuilder sb = new StringBuilder();
while (!temp.StandardOutput.EndOfStream)
{
    char[] buffer = new char[1024];
    temp.StandardOutput.Read(buffer, 0, buffer.Length);
    sb.Append(buffer);
    // Check output string and write something back if needed
    if (sb.ToString().Contains("(Yes/No"))
    {
        temp.StandardInput.WriteLine("Y");
        sb.Clear();
    }
}
temp.WaitForExit();

对,答案很简单。为了使用提示符成功启动静默cmd命令,我使用了以下添加项(示例适用于gpupdate /force)

 string cmdText = @"/c echo n | gpupdate /force";
 System.Diagnostics.Process temp = new System.Diagnostics.Process();          
 temp.StartInfo.Arguments = cmdText;
 temp.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
 temp.StartInfo.CreateNoWindow = true;
 temp.StartInfo.FileName = "cmd.exe";
 temp.EnableRaisingEvents = true;
 temp.Start();
 temp.WaitForExit();

答案在这里。感谢Stephan Bauer为我们指明了正确的方向

据我所知,echo n只是写n作为提示符。