.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#數(shù)據(jù)結(jié)構(gòu)之堆棧(Stack)實例詳解
這篇文章主要介紹了C#數(shù)據(jù)結(jié)構(gòu)之堆棧(Stack),結(jié)合實例形式較為詳細的分析了堆棧的原理與C#實現(xiàn)堆棧功能的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-11-11
C#?將Excel轉(zhuǎn)為PDF時自定義表格紙張大小的代碼思路
這篇文章主要介紹了C#?將Excel轉(zhuǎn)為PDF時自定義表格紙張大小的代碼思路,轉(zhuǎn)換前的頁面大小設(shè)置為該版本中寫入的新功能,在舊版本和免費版本中暫不支持,感興趣的朋友跟隨小編一起看看實例代碼2021-11-11
C# 實現(xiàn)視頻監(jiān)控系統(tǒng)(附源碼)
這篇文章主要介紹了C# 如何實現(xiàn)視頻監(jiān)控系統(tǒng),幫助大家更好的理解和使用c#,感興趣的朋友可以了解下2021-02-02

