在C#.NET GUI应用程序中。我还需要在后台安装控制台来执行某些任务。基本上,我正在使用Thrid Party库进行一些处理(花费大量时间),将其中间结果写入控制台。该处理是计算时间任务。所以,我将此任务分配给后台工作人员。我的意思是后台工作者调用这些库函数。但问题是我没有办法显示用户的计算状态,因为我没有库的来源。我希望控制台能够出现。但令人惊讶的是Console.WriteLine
似乎不起作用。我的意思是,没有显示任何控制台窗口。怎么样?
修改
我尝试设置应用程序类型=控制台。但似乎有一个问题。只有,主线程才能访问控制台。主(应用程序)线程仅执行Console.WriteLine
s显示在控制台上。 Console.WriteLine
由GUI的其他(BackgroundWorker)线程执行,输出未显示。我只需要后台工作人员的控制台。我的意思是,当后台工作人员启动时,控制台启动&当它结束时控制台将关闭。
答案 0 :(得分:2)
创建自己的控制台窗口并使用 Console.SetOut(myTextWriter); 方法读取写入控制台的任何内容。
答案 1 :(得分:1)
将您的应用程序类型设置为“控制台应用程序”。控制台应用程序也可以创建没有问题的GUI窗口,同时写入控制台。
如果您无法控制主应用程序,并且想要确保显示控制台,则可以p / invoke AllocConsole
(signature here)。
这与作为控制台应用程序不同,您的应用程序将始终获得单独的控制台窗口,这对于从命令提示符窗口启动它的人来说可能会令人惊讶。您可以使用AttachConsole
(s ignature and example here)来解决这个问题,但输出的shell重定向仍然不起作用。这就是我建议将应用程序子系统设置为控制台的原因。
答案 2 :(得分:0)
接下来是@jgauffin,这是Console.SetOut
方法的实现。
创建一个TextWriter
继承的类。
using System;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace ConsoleRedirection
{
public class TextBoxStreamWriter : TextWriter
{
TextBox _output = null;
public TextBoxStreamWriter(TextBox output)
{
_output = output;
}
public override void Write(char value)
{
base.Write(value);
_output.AppendText(value.ToString()); // When character data is written, append it to the text box.
}
public override Encoding Encoding
{
get { return System.Text.Encoding.UTF8; }
}
}
}
在表格中,代码如下。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace ConsoleRedirection
{
public partial class FormConsole : Form
{
// That's our custom TextWriter class
TextWriter _writer = null;
public FormConsole()
{
InitializeComponent();
}
private void FormConsole_Load(object sender, EventArgs e)
{
// Instantiate the writer
_writer = new TextBoxStreamWriter(txtConsole);
// Redirect the out Console stream
Console.SetOut(_writer);
Console.WriteLine("Now redirecting output to the text box");
}
// This is called when the "Say Hello" button is clicked
private void txtSayHello_Click(object sender, EventArgs e)
{
// Writing to the Console now causes the text to be displayed in the text box.
Console.WriteLine("Hello world");
}
}
}
原始代码来自https://saezndaree.wordpress.com/2009/03/29/how-to-redirect-the-consoles-output-to-a-textbox-in-c/ 您可以在评论中查看跨线程调用和高级实现的链接。