This is a swamp I have waded in, before. The cheap solution: put code to update the TextBox caret in the Form's 'Shown event handler. But, if you want to make the TextBox as independent as possible of its container, and, assuming: 1. this is a WinForm app with a TextBox set to show a vertical scrollbar 2. you will set the Text property at design time, or in the 'Load event of its container. 3. when the Form is shown, you want the TextBox scrolled to the end, and the TextBox selected/focused so if you start typing, what you type is added to the TextBox:
using System;
using System.Windows.Forms;
namespace YOURNAMESPACE
{
public partial class AutoScrolledTbx : UserControl // contains a TextBox
{
public AutoScrolledTbx()
{
InitializeComponent();
}
// for use creating an instance in code at run-time
public AutoScrolledTbx(string txt)
{
textBox1.Text = txt;
this.textBox1.Select(this.textBox1.TextLength + 1, 0);
this.textBox1.ScrollToCaret();
this.textBox1.Capture = true;
this.textBox1.Focus();
}
private void AutoScrolledTbx\_Load(object sender, EventArgs e)
{
// Marc Gravell
this.BeginInvoke((MethodInvoker)this.ForceScroll);
}
// adapted from Marc Gravell
// https://stackoverflow.com/a/218740/133321
private void ForceScroll()
{
// UI thread update
this.Invoke(
(MethodInvoker)delegate
{
this.textBox1.Select(this.textBox1.TextLength + 1, 0);
this.textBox1.ScrollToCaret();
this.textBox1.Focus();
ActiveControl = this.textBox1;
}
);
}
// public method to add text
public void AppendText(string txt)
{
this.textBox1.AppendText(txt);
}
}
}
Discussion: When a Form is being 'Loaded, then displayed, Controls may not appear in an expected state. By pushing a task onto the UI thread using Marc Gravell's technique shown here, you have achieved the equivalent of executing the update code in the Form's 'Shown event. In case you wonder why a UserControl is used here, rather than a sub-classed TextBox: a TextBox offers no 'Load or other initialization event to manipulate.
«