Kenyanke February 2016

How to output Debug Information to a RichTextBox?

I'm creating an FTP client and I wish to output the responses to a RichTextBox by outputting the debug information.

Would anyone be able to help on how to do this? Thanks

public FileARK()
{
    InitializeComponent();
    hostAddress.Text = "host";
    UserName.Text = "foo";
    Password.Text = "bar";
    //FtpTrace.AddListener(new TextWriterTraceListener(responseWindow.Text));
   // Debug.WriteLine(responseWindow.Text);
}

private void Connect_Click(object sender, EventArgs e)
{
    conn = new FtpClient();
    conn.Host = hostAddress.Text;
    conn.Credentials = new NetworkCredential(UserName.Text, Password.Text);
    conn.Connect();


}

private void Disconnect_Click(object sender, EventArgs e)
{
    conn.Disconnect();
}

private void responseWindow_TextChanged(object sender, EventArgs e)
{

}

Answers


rene February 2016

You can implement your own TraceListener that gets configured in the app.config and dynamically tries to find a richtextbox that matches the name in the config.

Your class can look like this:

public class TextBoxListener : TraceListener
{
    RichTextBox _box;
    string _data;
    public TextBoxListener(string initializeData)
    {
        _data = initializeData;
    }

    private bool Init()
    {
        if (_box != null && _box.IsDisposed )
        {
            // back to null if the control is disposed
            _box = null;
        }
        // find the logger text box
        if (_box == null)
        {
            // open forms
            foreach (Form f in Application.OpenForms)
            {
                // controls on those forms
                foreach (Control c in f.Controls)
                {
                    // does the name match 
                    if (c.Name == _data && c is RichTextBox)
                    {
                        // found one!
                        _box = (RichTextBox) c;
                        break;
                    }
                }
            }
        }
        return _box != null && !_box.IsDisposed;
    }

    public override void WriteLine(string message)
    {
        if (Init())
        {
            _box.Text = _box.Text + message + "\r\n";
        }
    }

    public override void Write(string message)
    {
        if (Init())
        {
            _box.Text = _box.Text + message;
        }
    }
}

Most important part of this class is the Init method that iterates over all openforms and all controls to find an richtextbox control that matches the name that is configured in the app.config.

To make use of this class configure tracing in your app.config and

Post Status

Asked in February 2016
Viewed 2,904 times
Voted 8
Answered 1 times

Search




Leave an answer