C#獲取命令行輸出內容的方法簡介
private void button3_Click(object sender, EventArgs e)
{
using (Process process = new System.Diagnostics.Process())
{
process.StartInfo.FileName = "ping";
process.StartInfo.Arguments = "www.ymind.net -t";
// 必須禁用操作系統外殼程序
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
// 異步獲取命令行內容
process.BeginOutputReadLine();
// 爲異步獲取訂閱事件
process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
}
}
private void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
// 這裏僅做輸出的示例,實際上您可以根據情況取消獲取命令行的內容
// 參考:process.CancelOutputRead()
if (String.IsNullOrEmpty(e.Data) == false)
this.AppendText(e.Data + "\r\n");
}
#region 解決多線程下控件訪問的問題
public delegate void AppendTextCallback(string text);
public void AppendText(string text)
{
if (this.textBox1.InvokeRequired)
{
AppendTextCallback d = new AppendTextCallback(AppendText);
this.textBox1.Invoke(d, text);
}
else
{
this.textBox1.AppendText(text);
}
}
#endregion
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.