RichTextbox 不公开 Paint 事件。所以很难在实际的控制表面上绘画。相反,我直接在 RichTextbox 旁边添加了一个简单的 PictureBox 以获得类似的效果。通过一些简单的数学计算,确定画线的位置,然后 DrawLine 完成这项工作。
加载事件
在这里设置我们要绘制的位图。
private void Form3_Load(object sender, EventArgs e)
{
this.richTextBox1.Text = Texts.Lorem;
// Create an bitmap
pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height);
}
按钮点击
当我们开始搜索时,确定搜索文本的位置,然后计算绘制线条的位置
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);
pictureBox1.Invalidate();
}
}
}
表格关闭
别忘了清理位图
private void Form3_FormClosed(object sender, FormClosedEventArgs e)
{
var bmp = pictureBox1.Image as IDisposable;
if (bmp!= null )
{
bmp.Dispose();
}
}
运行时会得到以下结果: