即時嘗試幾天來實時「捕獲」命令提示符的輸出,目前爲止我所做的最好的事情是以下內容,它同步啓動cmd並異步輸出的閱讀(我無法想出任何其他方式來實時完成)。事情是,應用程序中的命令繼續像平常一樣,而不是等待cmd上的進程完成。即在cmd完成其操作之前彈出消息框。感謝您的每一個回答:)同步打開命令提示符並在文本框中顯示輸出
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Threading;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public bool progressbool = false;
public string strOutput;
public string pathforit = Directory.GetCurrentDirectory();
public string line;
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
public Form1()
{
InitializeComponent();
commandline();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void commandline()
{
pProcess.StartInfo.FileName = "cmd.exe";
pProcess.StartInfo.UseShellExecute = false;
pProcess.StartInfo.RedirectStandardInput = true;
pProcess.StartInfo.RedirectStandardOutput = true;
pProcess.StartInfo.CreateNoWindow = true;
pProcess.Exited += new EventHandler(myProcess_Exited);
pProcess.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_OutputDataReceived);
pProcess.Start();
pProcess.BeginOutputReadLine();
pProcess.StandardInput.WriteLine("dir");
}
void process_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
{
this.AddText(e.Data);
}
delegate void AddTextCallback(string text);
private void AddText(string text)
{
if (this.textBox1.InvokeRequired)
{
AddTextCallback d = new AddTextCallback(AddText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox1.Text += text + Environment.NewLine;
textBox1.SelectionStart = textBox1.Text.Length;
textBox1.ScrollToCaret();
textBox1.Refresh();
}
}
private void myProcess_Exited(object sender, System.EventArgs e)
{
MessageBox.Show("The commands Operations have finished");
}
}
+1暗示的東西,你告訴他不要做。 :) – Nathan
感謝您的答案,我真的很感激它。我編輯了上面的代碼以顯示它現在是怎麼回事,問題是如果我運行該程序,該過程永遠不會結束,因此不會得到消息框 – Stefanou
@Stefanou:除非執行'exit',否則'cmd'永遠不會退出。 – SLaks