C#隱式運行CMD命令(隱藏命令窗口)
更新時間:2015年06月16日 11:13:30 投稿:junjie
這篇文章主要介紹了C#隱式運行CMD命令(隱藏命令窗口),本文實現(xiàn)在winform窗口中運行CMD命令,需要的朋友可以參考下
本文實現(xiàn)了C#隱式運行CMD命令的功能。下圖是實例程序的主畫面。在命令文本框輸入DOS命令,點擊“Run”按鈕,在下面的文本框中輸出運行結果。
下面是程序的完整代碼。本程序沒有使用p.StandardOutput.ReadtoEnd()和p.StandardOutput.ReadLine()方法來獲得輸出,因為這些方法執(zhí)行后畫面容易卡死。而是通過調(diào)用異步方法BeginOutputReadLine來獲取輸出,并在事件p.OutputDataReceived的事件處理方法中來處理結果。
using System; using System.Diagnostics; using System.IO; using System.Windows.Forms; namespace RunDosCommandForm { publicpartialclassForm1 : Form { publicForm1() { InitializeComponent(); } privatevoidbutton1_Click(object sender, EventArgse) { ExcuteDosCommand(textBox1.Text); } privatevoidExcuteDosCommand(string cmd) { try { Process p = newProcess(); p.StartInfo.FileName = "cmd"; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = true; p.OutputDataReceived += newDataReceivedEventHandler(sortProcess_OutputDataReceived); p.Start(); StreamWriter cmdWriter = p.StandardInput; p.BeginOutputReadLine(); if (!String.IsNullOrEmpty(cmd)) { cmdWriter.WriteLine(cmd); } cmdWriter.Close(); p.WaitForExit(); p.Close(); } catch(Exception ex) { MessageBox.Show("執(zhí)行命令失敗,請檢查輸入的命令是否正確!"); } } privatevoidsortProcess_OutputDataReceived(object sender,DataReceivedEventArgs e) { if(!String.IsNullOrEmpty(e.Data)) { this.BeginInvoke(newAction(() => { this.listBox1.Items.Add(e.Data);})); } } } }
我們還可以將需要運行的CMD命令保存為BAT文件,再使用Process類來執(zhí)行。
Process p = new Process();//設定調(diào)用的程序名,不是系統(tǒng)目錄的需要完整路徑 p.StartInfo.FileName = "cmd.bat";//傳入執(zhí)行參數(shù) p.StartInfo.Arguments = ""; p.StartInfo.UseShellExecute = false;//是否重定向標準輸入 p.StartInfo.RedirectStandardInput = false;//是否重定向標準轉(zhuǎn)出 p.StartInfo.RedirectStandardOutput = false;//是否重定向錯誤 p.StartInfo.RedirectStandardError = false;//執(zhí)行時是不是顯示窗口 p.StartInfo.CreateNoWindow = true;//啟動 p.Start(); p.WaitForExit(); p.Close();
您可能感興趣的文章:
相關文章
C#?基于TCP?實現(xiàn)掃描指定ip端口的方式示例
本文主要介紹了C#基于TCP實現(xiàn)掃描指定ip端口的方式示例,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11