利用WinForm的textBox实现控制台的Console.WriteLine
程序员文章站
2022-04-09 20:24:58
...
重写WriteLine与Write方法,重写后Console.WriteLine将直接写到Winform的textBox框中,不受类库的限制。
public class ConsoleHelper : TextWriter
{
private System.Windows.Forms.TextBox _textBox { set; get; }
private int maxRowLenght = 200;//textBox中显示的最大行数,若不限制,则置为0
public ConsoleHelper(System.Windows.Forms.TextBox textBox)
{
this._textBox = textBox;
Console.SetOut(this);
}
public override void Write(string value)
{
if (_textBox.IsHandleCreated)
_textBox.BeginInvoke(new ThreadStart(() =>
{
if(maxRowLenght > 0 && _textBox.Lines.Lenght > maxRowLenght)
{
int strat = _textBox.GetFirstCharIndexFromLine(0);//获取第0行第一个字符的索引
int end = _textBox.GetFirstCharIndexFromLine(10);
_textBox.Select(strat,end);//选择文本框中的文本范围
_textBox.SelectedText = "";//将当前选定的文本内容置为“”
_textBox.AppendText(value + " ");
}
else
{
_textBox.AppendText(value + " ");
}
}));
}
public override void WriteLine(string value)
{
if (_textBox.IsHandleCreated)
_textBox.BeginInvoke(new ThreadStart(() =>
{
if(maxRowLenght > 0 && _textBox.Lines.Lenght > maxRowLenght)
{
int strat = _textBox.GetFirstCharIndexFromLine(0);//获取第0行第一个字符的索引
int end = _textBox.GetFirstCharIndexFromLine(10);
_textBox.Select(strat,end);//选择文本框中的文本范围
_textBox.SelectedText = "";//将当前选定的文本内容置为“”
_textBox.AppendText(value + "\r\n");
}
else
{
_textBox.AppendText(value + "\r\n");
}
}));
}
public override Encoding Encoding//这里要注意,重写wirte必须也要重写编码类型
{
get { return Encoding.UTF8; }
}
}
然后在Form.cs中的Form()中初始化一下:
public Form()
{
InitializeComponent();
new ConsoleHelper(txt_this);//重写Console的Write与WriteLine
}
txt_this为要输出的目标textbox。
不想再向Form输出时,直接屏蔽 new ConsoleHelper(txt_this);
那么现在就可以在任何地方使用Console.WriteLine()来输出到Form中的textBox中了。