解決方法一:
自己放一個文本框,改成黑色,然后輸入命令,執行時,你Process.Start cmd ,此時CMD窗口不顯示,然后,將CMD的返回值,再取出來,設回文本框。
如何用這種方法實時獲取cmd返回的數據,簡單實現如下
1 private void OutPutForm_Shown(object sender, EventArgs e) 2 { 3 Control.CheckForIllegalCrossThreadCalls = false; 4 process = new Process(); 5 p.StartInfo.FileName = "cmd.exe"; 6 p.StartInfo.UseShellExecute = false; //是否使用操作系統shell啟動
7 p.StartInfo.RedirectStandardInput = true;//接受來自調用程序的輸入信息
8 p.StartInfo.RedirectStandardOutput = true;//由調用程序獲取輸出信息
9 p.StartInfo.RedirectStandardError = true;//重定向標准錯誤輸出
10 p.StartInfo.CreateNoWindow = true;//不顯示程序窗口
11 process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler); 12 process.Start();//啟動程序
13 process.BeginOutputReadLine(); 14 } 15 private void OutputHandler(object sendingProcess,DataReceivedEventArgs outLine) 16 { 17 if (!String.IsNullOrEmpty(outLine.Data)) 18 { 19 StringBuilder sb = new StringBuilder(this.textBox1.Text); 20 this.textBox1.Text = sb.AppendLine(outLine.Data).ToString(); 21 this.textBox1.SelectionStart =this.textBox1.Text.Length; 22 this.textBox1.ScrollToCaret(); 23 } 24 }
解決方法二:
直接上代碼
1 [DllImport("User32.dll ", EntryPoint = "SetParent")] 2 private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); 3 [DllImport("user32.dll ", EntryPoint = "ShowWindow")] 4 public static extern int ShowWindow(IntPtr hwnd, int nCmdShow); 5 private void button3_Click(object sender, EventArgs e) 6 { 7 Process p = new Process(); 8 p.StartInfo.FileName = "cmd.exe "; 9 p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized;//加上這句效果更好
10 p.Start(); 11 System.Threading.Thread.Sleep(100);//加上,100如果效果沒有就繼續加大
12
13 SetParent(p.MainWindowHandle, panel1.Handle); //panel1.Handle為要顯示外部程序的容器
14 ShowWindow(p.MainWindowHandle, 3); 15 }
備注:記得引用 using System.Runtime.InteropServices;


