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

