同步打开命令提示符并在文本框中显示输出

时间:2011-11-25 02:11:59

标签: c#

我现在尝试几天来实时“捕获”命令提示符的输出,到目前为止我做的最好的事情是以下,它同步启动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");
    }
}

2 个答案:

答案 0 :(得分:2)

你可以致电WaitForExit来做到这一点 但是,不要这样做;它会在等待时冻结您的程序 您永远不应该在UI线程上执行阻止操作。

相反,处理Exited事件并在那里显示消息框。

答案 1 :(得分:1)

尝试在Process上挂起Exited事件并将消息框放在

pProcess.Exited += // my exit handler