Hi mọi người, hôm nay Hùng Coder lượn lờ phố xá internet trong sáng hôm nay nhìn thấy bài viết này cũng khá hay về thủ thuật lấy dữ liệu từ Console Write rất thú vị, nên viết bài chia sẽ lại cho mọi người rỏ luôn nè :D.

Trong lập trình ứng dụng Winform, các bạn thường sử dụng Console.Write để xuất dữ liệu ra để chúng ta test (log).
Và mong muốn là mình muốn hiển thị log đó từ Console.Write() vào TextBox Winform.


Để thực hiện được việc này đầu tiên các bạn thêm một class : TextBoxStreamWriter.cs
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());

}

public override Encoding Encoding
{
get { return System.Text.Encoding.UTF8; }
}
}
}

Tiếp theo trong FormConsole.cs các bạn sữ dụng như sau.
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
{
TextWriter _writer = null;

public FormConsole()
{
InitializeComponent();
}

private void FormConsole_Load(object sender, EventArgs e)
{
_writer = new TextBoxStreamWriter(txtConsole);
Console.SetOut(_writer);

Console.WriteLine("Now redirecting output to the text box");
}

private void txtSayHello_Click(object sender, EventArgs e)
{
Console.WriteLine("Hello world");
}
}
}
Và bây giờ bất kỳ ở Form nào xuất Console.Write thì ở FormConsole này đều hiển thị dữ liệu đó lên textbox. Như vậy đã hoàn thành rồi đấy.

Hi sorrry mọi người nha, do thời gian Hùng hạn chế quá nên chưa có thể ra mắt DEMOVIDEO cho các bạn được.
Chúc các bạn thành công với thủ thuật đơn giản và khá hay này.