.NET程序頁面中,操作并輸入cmd命令的小例子
WinFormsApp_OperateAndInputCMD:
新建Form1,拖入TextBox,并設(shè)為允許多行,Dock設(shè)為Fill,然后綁定KeyUp事件即可
執(zhí)行代碼如下:
private void txtCmdInput_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
int count = txtCmdInput.Lines.Length;
if (count == 0) return;
while (count > 0 && (string.IsNullOrEmpty(txtCmdInput.Lines[count - 1])))
{
count--;
}
if (count > 0)// && !string.IsNullOrEmpty(txtCmdInput.Lines[count - 1]))
ExecuteCmd(txtCmdInput.Lines[count - 1]);
}
}
public void ExecuteCmd(string cmd)
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start(); //設(shè)置自動刷新緩沖并更新
p.StandardInput.AutoFlush = true; //寫入命令
p.StandardInput.WriteLine(cmd);
p.StandardInput.WriteLine("exit"); //等待結(jié)束
txtCmdInput.AppendText(p.StandardOutput.ReadToEnd());
p.WaitForExit();
p.Close();
}
執(zhí)行效果圖:
相關(guān)文章
C#使?XmlReader和XmlWriter操作XML?件
這篇文章介紹了C#使?XmlReader和XmlWriter操作XML?件的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06

