Alex Angas
Alex Angas

Reputation: 60047

Logging to a text box with auto-follow cursor

I'm using a WinForms TextBox control for logging. It's been set as multiline with scrollbars. I'm inserting text by using:

textBox.Text += logMessage;

The scrollbar does not automatically follow with the latest log entry. Is there a way to do this?

Upvotes: 1

Views: 526

Answers (2)

Tim Coker
Tim Coker

Reputation: 6524

I'm late to the party, but the thing to be careful when logging like this is the length of your text field. You want to trim the head of it every so often (but not too often...). The strategy I've used is to use a max character limit, say 5000, and when that text reaches double the limit, cut it down to the limit.

string LimitText(string Text)
{
    int textLimit = 5000;
    //let the field grow to double the limit, then chop it in half
    if (Text.Length > textLimit * 2)
    {
        Text = Text.Substring(Text.Length - textLimit, textLimit);
    }
    return Text;
}

The double limit thing is there to reduce the occurrence of substring operations. Also, this is really only an issue if you use this in a long running programs that continuously add to the text field. (Yes, I also log to a text file and normally use that for debugging. This is more for quick diagnostics...)

Upvotes: 1

icktoofay
icktoofay

Reputation: 129079

Set the TextBox's SelectionStart property to the length of the text, then call ScrollToCaret.

Upvotes: 1

Related Questions