C#隱式運轉CMD敕令(隱蔽敕令窗口)。本站提示廣大學習愛好者:(C#隱式運轉CMD敕令(隱蔽敕令窗口))文章只能為提供參考,不一定能成為您想要的結果。以下是C#隱式運轉CMD敕令(隱蔽敕令窗口)正文
本文完成了C#隱式運轉CMD敕令的功效。下圖是實例法式的主畫面。在敕令文本框輸出DOS敕令,點擊“Run”按鈕,鄙人面的文本框中輸入運轉成果。

上面是法式的完全代碼。本法式沒有應用p.StandardOutput.ReadtoEnd()和p.StandardOutput.ReadLine()辦法來取得輸入,由於這些辦法履行後畫面龐易卡逝世。而是經由過程挪用異步辦法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("履行敕令掉敗,請檢討輸出的敕令能否准確!");
}
}
privatevoidsortProcess_OutputDataReceived(object sender,DataReceivedEventArgs e)
{
if(!String.IsNullOrEmpty(e.Data))
{
this.BeginInvoke(newAction(() => { this.listBox1.Items.Add(e.Data);}));
}
}
}
}
我們還可以將須要運轉的CMD敕令保留為BAT文件,再應用Process類來履行。
Process p = new Process();//設定挪用的法式名,不是體系目次的須要完全途徑 p.StartInfo.FileName = "cmd.bat";//傳入履行參數 p.StartInfo.Arguments = ""; p.StartInfo.UseShellExecute = false;//能否重定向尺度輸出 p.StartInfo.RedirectStandardInput = false;//能否重定向尺度轉出 p.StartInfo.RedirectStandardOutput = false;//能否重定向毛病 p.StartInfo.RedirectStandardError = false;//履行時是否是顯示窗口 p.StartInfo.CreateNoWindow = true;//啟動 p.Start(); p.WaitForExit(); p.Close();