How to append text to RichTextBox without scrolling and losing selection?

I need to append text to RichTextBox, and need to perform it without making text box scroll or lose current text selection, is it possible?

The RichTextBox in WinForms is quite flicker happy when you play around with the text and select-text methods.

I have a standard replacement to turn off the painting and scrolling with the following code:

class RichTextBoxEx: RichTextBox
{
  [DllImport("user32.dll")]
  static extern IntPtr SendMessage(IntPtr hWnd, Int32 wMsg, Int32 wParam, ref Point lParam);

  [DllImport("user32.dll")]
  static extern IntPtr SendMessage(IntPtr hWnd, Int32 wMsg, Int32 wParam, IntPtr lParam);

  const int WM_USER = 0x400;
  const int WM_SETREDRAW = 0x000B;
  const int EM_GETEVENTMASK = WM_USER + 59;
  const int EM_SETEVENTMASK = WM_USER + 69;
  const int EM_GETSCROLLPOS = WM_USER + 221;
  const int EM_SETSCROLLPOS = WM_USER + 222;

  Point _ScrollPoint;
  bool _Painting = true;
  IntPtr _EventMask;
  int _SuspendIndex = 0;
  int _SuspendLength = 0;

  public void SuspendPainting()
  {
    if (_Painting)
    {
      _SuspendIndex = this.SelectionStart;
      _SuspendLength = this.SelectionLength;
      SendMessage(this.Handle, EM_GETSCROLLPOS, 0, ref _ScrollPoint);
      SendMessage(this.Handle, WM_SETREDRAW, 0, IntPtr.Zero);
      _EventMask = SendMessage(this.Handle, EM_GETEVENTMASK, 0, IntPtr.Zero);
      _Painting = false;
    }
  }

  public void ResumePainting()
  {
    if (!_Painting)
    {
      this.Select(_SuspendIndex, _SuspendLength);
      SendMessage(this.Handle, EM_SETSCROLLPOS, 0, ref _ScrollPoint);
      SendMessage(this.Handle, EM_SETEVENTMASK, 0, _EventMask);
      SendMessage(this.Handle, WM_SETREDRAW, 1, IntPtr.Zero);
      _Painting = true;
      this.Invalidate();
    }
  }
}

and then from my form, I can happily have a flicker-free richtextbox control:

richTextBoxEx1.SuspendPainting();
richTextBoxEx1.AppendText("Hey!");
richTextBoxEx1.ResumePainting();

How to: C#, I need to append text to RichTextBox, and need to perform it without making text box scroll or lose current text selection, is it possible? The RichTextBox in WinForms is quite flicker happy when you play around with the text and select-text methods. I have a standard replacement to turn off the painting and scrolling with the following code:

based on LarsTech article here something nice:

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;

namespace yournamespace
{
    class RichTextBoxEx : RichTextBox
    {
        [DllImport("user32.dll")]
        static extern IntPtr SendMessage(IntPtr hWnd, Int32 wMsg, Int32 wParam, ref Point lParam);

        [DllImport("user32.dll")]
        static extern IntPtr SendMessage(IntPtr hWnd, Int32 wMsg, Int32 wParam, IntPtr lParam);

        const int WM_USER = 0x400;
        const int WM_SETREDRAW = 0x000B;
        const int EM_GETEVENTMASK = WM_USER + 59;
        const int EM_SETEVENTMASK = WM_USER + 69;
        const int EM_GETSCROLLPOS = WM_USER + 221;
        const int EM_SETSCROLLPOS = WM_USER + 222;

        Point _ScrollPoint;
        bool _Painting = true;
        IntPtr _EventMask;
        int _SuspendIndex = 0;
        int _SuspendLength = 0;

        public bool Autoscroll = true;

        public void SuspendPainting()
        {
            if (_Painting)
            {
                _SuspendIndex = this.SelectionStart;
                _SuspendLength = this.SelectionLength;
                SendMessage(this.Handle, EM_GETSCROLLPOS, 0, ref _ScrollPoint);
                SendMessage(this.Handle, WM_SETREDRAW, 0, IntPtr.Zero);
                _EventMask = SendMessage(this.Handle, EM_GETEVENTMASK, 0, IntPtr.Zero);
                _Painting = false;
            }
        }

        public void ResumePainting()
        {
            if (!_Painting)
            {
                this.Select(_SuspendIndex, _SuspendLength);
                SendMessage(this.Handle, EM_SETSCROLLPOS, 0, ref _ScrollPoint);
                SendMessage(this.Handle, EM_SETEVENTMASK, 0, _EventMask);
                SendMessage(this.Handle, WM_SETREDRAW, 1, IntPtr.Zero);
                _Painting = true;
                this.Invalidate();
            }
        }

        new public void AppendText(string text)  // overwrites RichTextBox.AppendText
        {
            if (Autoscroll)
                base.AppendText(text);
            else
            {
                SuspendPainting();
                base.AppendText(text);
                ResumePainting();
            }
        }
    }
}

you can use it like this:

var textbox = new RichTextBoxEx();
textbox.Autoscroll = false;

textbox.AppendText("Hi");

RichTextBox Class (System.Windows.Controls), Prevent a RichTextBox control from automatically scrolling to the bottom when appending text. How to append text to a RichTextBox control without it automatically scrolling to If there is no focus, text can not be selected, copied, etc. To regain this lost functionality, some event handlers need to be added� Public ReadOnly Property Selection As TextSelection Property Value TextSelection. A TextSelection object containing the current selection in the RichTextBox. The default returned TextSelection has an IsEmpty property value of true. An empty TextSelection renders as a caret in the text area with no selection. Examples

VB.NET Richtextbox help with Hightlighting with Auto scroll., Add(new Paragraph(new Run("Paragraph 3"))); RichTextBox myRichTextBox = new you deliberately want to disable RichTextBox native handling of these events, and To make a scrollbar visible, set the VerticalScrollBarVisibility property to Gets or sets a value that indicates whether the text box displays selected text� The following code example demonstrates how to align text within the RichTextBox. This example requires that a RichTextBox control, named richTextBox1 , has been added to the form. private: void WriteCenteredTextToRichTextBox() { // Clear all text from the RichTextBox; richTextBox1->Clear(); // Set the foreground color of the text.

Modified LarsTech code to automatically stop auto scrolling if caret is not at the last position in the RichTextBox. Also solved the problem with entering colored text. To resume scrolling put caret at the last position (Ctrl-END)

    class RichTextBoxEx : RichTextBox
    {
        [DllImport("user32.dll")]
        private static extern IntPtr SendMessage(IntPtr hWnd, Int32 wMsg, Int32 wParam, ref Point lParam);

        [DllImport("user32.dll")]
        private static extern IntPtr SendMessage(IntPtr hWnd, Int32 wMsg, Int32 wParam, IntPtr lParam);

        [DllImport("user32")]
        private static extern int GetCaretPos(out Point p);

        const int WM_USER = 0x400;
        const int WM_SETREDRAW = 0x000B;
        const int EM_GETEVENTMASK = WM_USER + 59;
        const int EM_SETEVENTMASK = WM_USER + 69;
        const int EM_GETSCROLLPOS = WM_USER + 221;
        const int EM_SETSCROLLPOS = WM_USER + 222;

        private Point oScrollPoint;
        private bool bPainting = true;
        private IntPtr oEventMask;
        private int iSuspendCaret;
        private int iSuspendIndex;
        private int iSuspendLength;
        private bool bWasAtEnd;
        private Color _selColor = Color.Black;

        public int CaretIndex
        {
            get
            {
                Point oCaret;
                GetCaretPos(out oCaret);
                return this.GetCharIndexFromPosition(oCaret);
            }
        }

        new public Color SelectionColor { get { return _selColor; } set { _selColor = value; } }
        new public void AppendText(string text)  // overwrites RichTextBox.AppendText
        {
            if (this.SelectionStart >= this.TextLength)
            {
                base.SelectionColor = _selColor;
                base.AppendText(text);
            }
            else
            {
                var selStart = this.SelectionStart;
                var selLength = this.SelectionLength;
                SuspendPainting();
                this.Select(this.TextLength, 0);
                base.SelectionColor = _selColor;
                base.AppendText(text);
                this.Select(selStart, selLength);
                ResumePainting();
            }
        }
        private void SuspendPainting()
        {
            if (this.bPainting)
            {
                this.iSuspendCaret = this.CaretIndex;
                this.iSuspendIndex = this.SelectionStart;
                this.iSuspendLength = this.SelectionLength;
                this.bWasAtEnd = this.iSuspendIndex + this.iSuspendLength == this.TextLength;

                SendMessage(this.Handle, EM_GETSCROLLPOS, 0, ref this.oScrollPoint);
                SendMessage(this.Handle, WM_SETREDRAW, 0, IntPtr.Zero);
                this.oEventMask = SendMessage(this.Handle, EM_GETEVENTMASK, 0, IntPtr.Zero);
                this.bPainting = false;
            }
        }

        private void ResumePainting()
        {
            if (!this.bPainting)
            {
                if (this.iSuspendLength == 0)
                {
                    if (!bWasAtEnd)
                    {
                        this.Select(this.iSuspendIndex, 0);
                    }
                }
                else
                {
                    // Original selection was to end of text
                    if (bWasAtEnd)
                    {
                        // Maintain end of selection at end of new text
                        this.iSuspendLength = this.TextLength - this.iSuspendIndex;
                    }

                    if (this.iSuspendCaret > this.iSuspendIndex)
                    {
                        // Forward select (caret is at end)
                        this.Select(this.iSuspendIndex, this.iSuspendLength);
                    }
                    else
                    {
                        // Reverse select (caret is at start)
                        this.Select(this.iSuspendIndex + this.iSuspendLength, -this.iSuspendLength);
                    }
                }
                SendMessage(this.Handle, EM_SETSCROLLPOS, 0, ref this.oScrollPoint);
                SendMessage(this.Handle, EM_SETEVENTMASK, 0, this.oEventMask);
                SendMessage(this.Handle, WM_SETREDRAW, 1, IntPtr.Zero);
                this.bPainting = true;
                this.Invalidate();
            }
        }
    }

RichTextBox in C#, Remove From My Forums Select(RichTextBox1. What my issue is line will highlight but when it auto scrolls I lose the highlightling. Use the RichTextBox method AppendText to add a string to the end of the text. See:. One way to append text to a RichTextBox is simply set Text property to current text plus new text you would want to append something like this. RichTextBox1.Text += " Appended text" RichTextBox also has the ApendText method to do the same. The AppendText method appends text at the end of a RichTextBox.

This should do what you want:

        Dim tempStart As Int32
    Dim tempLength As Int32

    tempStart = RichTextBox1.SelectionStart
    tempLength = RichTextBox1.SelectionLength

    RichTextBox1.Text += "dsfkljwerhsdlf"

    RichTextBox1.SelectionStart = tempStart
    RichTextBox1.SelectionLength = tempLength

The RichTextBox Control, A RichTextBox control is an advanced text box that provides text editing and One way to append text to a RichTextBox is simply set Text property to current and they will be visible when the scrolling is needed on a RichTextBox control. The following code snippet sets the selection on a RichTextBox. If the file does exist, write operations to the StreamWriter append text to the file. Additional threads are permitted to read the file while it is open. The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory.

The TextBox Control, Only selected text can be assigned character and paragraph formatting. To insert objects into the RichTextBox control, you simply drag a file (from the Windows that determines whether selected text appears highlighted when the RTB loses focus. Scroll bars can be added to to a larger RichTextBox control using the� Searches the text in a RichTextBox control for a string at a specific location within the control and with specific options applied to the search. Find(Char[], Int32, Int32) Searches a range of text in a RichTextBox control for the first instance of a character from a list of characters. Find(Char[])

Add to TextBox, prevent scrolling-VBForums, AppendText, Appends text to the text in the text box to the ForeColor property effective, use a RichTextBox or change the Use the ScrollBars property to enable and disable horizontal and vertical scroll bars on multiline textboxes. Instead of the typed character, a character selected by the operating�

C# Windows Forms, I have a textbox to which text is continuously appended (every second It leaves the selection untouched was there before first, so any scrolling position is lost at that point. The point is just to give the user the opportunity to look at the contents of the TextBox calmly and without getting disturbed by any�

Comments
  • Interesting. Have you ever tried .DoubleBuffered property on the form?
  • @Robert DoubleBuffering the form won't automatically DoubleBuffer the child controls. Although there have been lots of creative ways to try it.
  • @AdamBruss It should work. Why it doesn't work for you??? I don't see your code. Post a well documented question if you need help.
  • @AdamBruss OK, I reproduced it. If I enter enough text to produce a scrollbar, then scroll to the top and put the cursor on the first line, your appended output is now black instead of red. When you set the SelectionColor, your selection is not at the end, so you are coloring the wrong selection. I'll have to play around with a work around.
  • @AdamBruss The "hack" would be to supply an rtf string: rtb.Select(rtb.TextLength, 0); rtb.SelectedRtf = @"{\rtf\ansi{\colortbl;\red255\green0\blue0;}\cf1 Red String\par}";rtb.Select(rtb.TextLength, 0);rtb.SelectionColor = Color.Black;