c# RichTextBox 출력 빠르게 하기
RichTextBox.AppendText는 느리다. 수십 줄 출력하는 데에도 그려지는 게 보일 정도다. 아래의 방법들을 쓰면 빠르게 출력된다.
RichTextBox.BeginUpdate/EndUpdate 만들기
일반적인 비주얼 컨트롤들의 경우 BeginUpdate/EndUpdate가 있다면 이걸 쓰는 게 빠르다. AppendText로 추가되는 내용을 바로바로 출력하는 게 아니라 출력을 멈췄다가 추가할 것들을 다 추가한 뒤 한꺼번에 출력하는 거다. 하지만 RichTextBox에는 BeginUpdate/EndUpdate가 없다. 아래와 같이 상속해서 써야 한다.
public class RichTextBoxInherited : RichTextBox
{
[DllImport("user32")]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
private const int WM_SETREDRAW = 0x0b;
public void BeginUpdate()
{
SendMessage(Handle, WM_SETREDRAW, (IntPtr)0, IntPtr.Zero);
}
public void EndUpdate()
{
SendMessage(Handle, WM_SETREDRAW, (IntPtr)1, IntPtr.Zero);
Invalidate();
}
}
RichTextBoxInherited RichTextBoxInherited1;
private void Form1_Load(object sender, EventArgs e)
{
RichTextBoxInherited1 = new()
{
Width = 500,
Height = 500
};
Controls.Add(RichTextBoxInherited1);
}
private void Form1_Click(object sender, EventArgs e)
{
RichTextBoxInherited1.BeginUpdate();
for (int i = 0; i < 1000; i++)
{
RichTextBoxInherited1.AppendText("abcde\n");
}
RichTextBoxInherited1.EndUpdate();
}
String.Join 이용하기
더 좋은 방법은 아래와 같다.
StringBuilder stringBuilder = new();
stringBuilder.Append("abcde");
richTextBox1.Text = string.Join('\n', stringBuilder);
스타일을 적용해야 하는 경우에는 RichTextBox.Rtf를 이용하면 된다.