簡體   English   中英

將控制台輸出重定向到單獨程序中的文本框

[英]Redirect console output to textbox in separate program

我正在開發一個 Windows 窗體應用程序,它需要我調用一個單獨的程序來執行任務。 該程序是一個控制台應用程序,我需要將控制台的標准輸出重定向到我程序中的 TextBox。

我從我的應用程序執行程序沒有問題,但我不知道如何將輸出重定向到我的應用程序。 我需要在程序運行時使用事件捕獲輸出。

控制台程序不會停止運行,直到我的應用程序停止並且文本以隨機間隔不斷變化。 我正在嘗試做的只是從控制台掛鈎輸出以觸發事件處理程序,然后可以使用該事件處理程序更新 TextBox。

我使用 C# 編寫程序並使用 .NET 框架進行開發。 原始應用程序不是 .NET 程序。

編輯:這是我正在嘗試做的示例代碼。 在我的最終應用程序中,我將用代碼替換 Console.WriteLine 以更新 TextBox。 我試圖在我的事件處理程序中設置一個斷點,但它甚至沒有達到。

    void Method()
    {
        var p = new Process();
        var path = @"C:\ConsoleApp.exe";

        p.StartInfo.FileName = path;
        p.StartInfo.UseShellExecute = false;
        p.OutputDataReceived += p_OutputDataReceived;

        p.Start();
    }

    static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        Console.WriteLine(">>> {0}", e.Data);
    }

這對我有用:

void RunWithRedirect(string cmdPath)
{
    var proc = new Process();
    proc.StartInfo.FileName = cmdPath;

    // set up output redirection
    proc.StartInfo.RedirectStandardOutput = true;
    proc.StartInfo.RedirectStandardError = true;    
    proc.EnableRaisingEvents = true;
    proc.StartInfo.CreateNoWindow = true;
    // see below for output handler
    proc.ErrorDataReceived += proc_DataReceived;
    proc.OutputDataReceived += proc_DataReceived;

    proc.Start();

    proc.BeginErrorReadLine();
    proc.BeginOutputReadLine();

    proc.WaitForExit();
}

void proc_DataReceived(object sender, DataReceivedEventArgs e)
{
    // output will be in string e.Data
}

您可以使用以下代碼

        MemoryStream mem = new MemoryStream(1000);
        StreamWriter writer = new StreamWriter(mem);
        Console.SetOut(writer);

        Assembly assembly = Assembly.LoadFrom(@"C:\ConsoleApp.exe");
        assembly.EntryPoint.Invoke(null, null);
        writer.Close();

        string s = Encoding.Default.GetString(mem.ToArray());
        mem.Close();

我在O2 平台(開源項目)中添加了許多輔助方法,允許您通過控制台輸出和輸入輕松編寫與另一個進程的交互腳本(請參閱http://code.google.com/p/o2platform/源/瀏覽/主干/O2_Scripts/APIs/Windows/CmdExe/CmdExeAPI.cs )

同樣對您有用的可能是允許查看當前進程的控制台輸出(在現有控件或彈出窗口中)的 API。 有關更多詳細信息,請參閱此博客文章: http : //o2platform.wordpress.com/2011/11/26/api_consoleout-cs-inprocess-capture-of-the-console-output/ (此博客還包含有關如何使用新進程的控制台輸出)

感謝 Marc Maxham 的回答,節省了我的時間!

正如所有行業的 Jon 所注意到的,必須將UseShellExecute設置為 false 以重定向 IO 流,否則Start()調用會引發InvalidOperationException

這是我對代碼的修改,其中txtOut是 WPF 只讀文本框

void RunWithRedirect(string cmdargs)
{
    var proc = new Process()
    {
        StartInfo = new ProcessStartInfo("cmd.exe", "/k " + cmdargs)
        {
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true
        },
        EnableRaisingEvents = true
    };

    // see below for output handler
    proc.ErrorDataReceived += proc_DataReceived;
    proc.OutputDataReceived += proc_DataReceived;
    proc.Start();

    proc.BeginErrorReadLine();
    proc.BeginOutputReadLine();

    proc.WaitForExit();
}

void proc_DataReceived(object sender, DataReceivedEventArgs e)
{
    if (e.Data != null)
        Dispatcher.BeginInvoke(new Action( () => txtOut.Text += (Environment.NewLine + e.Data) ));
}

如果您需要實時輸出,您只需要手動讀取 StandardOutput。 我試過聽OutputDataReceived,但是OutputDataReceived只會在程序結束時一次性全部輸出,所以你無法觀察到實時輸出。這項工作。這對我有用。

static void Main(string[] args)
    {
        //
        // Setup the process with the ProcessStartInfo class.
        //
        ProcessStartInfo start = new ProcessStartInfo();
        start.FileName = @"your.exe"; // Specify exe name.
        start.UseShellExecute = false;
        start.RedirectStandardOutput = true;

        //
        // Start the process.
        //
        Process process = new Process();
        process.StartInfo = start;
        process.Start();
        readinfo(process);
        process.WaitForExit();//Call based on usage
    }

    static async void readinfo(Process process)
    {
        while (!process.HasExited)
        {
            string result = await process.StandardOutput.ReadLineAsync();
            Console.WriteLine(result);
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM