Friday, July 6, 2007

Making Textbox control autoscrollable

If text is appended every time, we can do this way:

txtBx->AppendText(strToAppend);
txtBx->Focus();
txtBx->ScrollToCaret();

If text is completely loaded from the beginning to the end every time, it can be done this way:

txtBx->Text = strContent;
txtBx->Focus();
txtBx->SelectionLength = 0;
txtBx->SelectionStart = txtBx->Text->Length;
txtBx->ScrollToCaret();

In either case, Focus method is indispensable.

2 comments:

Xiaoguang said...

Actually, when appending text, using only Focus method is enough. The tricky thing is, when calling the update text method from another thread other than the main thread, we need to switch the thread context explicitly to the main thread. That is, write a InvokeRequired condition statment in the update text method; use this->Invoke(...) when invoke is required.

Xiaoguang said...

public: void Append()
{
if (richTextBox1->InvokeRequired == false)
{
String* str = S"This is a long string\r\n";
richTextBox1->AppendText(str);
//richTextBox1->Text = str;
richTextBox1->Focus();
//richTextBox1->SelectionLength = 0;
//richTextBox1->SelectionStart = richTextBox1->Text->Length;
//richTextBox1->ScrollToCaret();
}
else
{
UpdateDelegateNoParam* ud = new UpdateDelegateNoParam(this, &Form1::Append);
this->Invoke(ud);
}
}

private: System::Void button1_Click(System::Object * sender, System::EventArgs * e)
{
UpdateDelegateNoParam* asyncCall = new UpdateDelegateNoParam(this, Append);
asyncCall->Invoke();
//asyncCall->BeginInvoke(NULL, NULL);
}