簡體   English   中英

C#隱藏的cmd窗口需要輸入

[英]C# Hidden cmd window require input

在我的代碼中,我需要運行許多cmd命令。 所有這些都必須隱藏。 作為示例,我將向您展示2個命令的代碼。

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?

您需要讀取程序的輸出並進行處理/將所需的輸入寫回到流程中。 為此,您還需要設置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寫入提示。 它將成功。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM