How to highlight in the background of a scrollbar of a richtextbox the relative position of a selected piece of text

I want to highlight the position of the selected text against the background of a richtextbox scrollbar. I mainly use the richtextbox.find command to find text. Then I highlight this text, so everything is fine. But I would also like to mark this position in the background of the scroll bar. So for the user, they would see that they need to scroll down to say a red line in the background of the scroll bar to find what they were looking for. This should work for several different words, which might be in different places in the text box.

An example of this is that on the left side of the left, it puts a small line in each place, the code does not match the revised copy. Therefore, you can quickly scroll through it.


source to share

1 answer

The RichTextbox does not display the Paint event. So it is difficult to draw on the control surface. Instead, I added a simple PictureBox directly next to the RichTextbox for a similar effect. With some simple math, you figure out the position where you want to draw the line and then DrawLine does the job.

Load event

Adjust the bitmap that we will be painting.

private void Form3_Load(object sender, EventArgs e)
    this.richTextBox1.Text = Texts.Lorem;
    // Create an bitmap 
    pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height);



Click on

When we start searching, we determine the position of the search text and then calculate the position to draw the line

private void button1_Click(object sender, EventArgs e)
    // find some text
    var index = this.richTextBox1.Find(this.textBox1.Text);
    if (index>-1)
        using (var gr = Graphics.FromImage(pictureBox1.Image))
            // calculate where to postion the bar
            var textpos = index / (double)this.richTextBox1.Text.Length;
            var position = (double) pictureBox1.Height * textpos;
            Trace.WriteLine(String.Format("{0}:{1}:{2}", index, textpos, position));

            // draw it
            gr.DrawLine(new Pen(Color.Red, 4), 0, (int)position, pictureBox1.Width, (int)position);


Closed form

Don't forget to clear the bitmap

private void Form3_FormClosed(object sender, FormClosedEventArgs e)
    var bmp = pictureBox1.Image as IDisposable;
    if (bmp!= null )


When you run this, you get:

demo of redline on position



All Articles