您需要创建自己的控件从RichTextBox继承并在窗体上使用该控件。由于RichTextBox不支持所有者绘图,因此您必须监听WM_PAINT消息,然后在那里完成您的工作。下面是一个很好的例子,虽然行高是现在硬编码的:
public class HighlightableRTB : RichTextBox
{
// You should probably find a way to calculate this, as each line could have a different height.
private int LineHeight = 15;
public HighlightableRTB()
{
HighlightColor = Color.Yellow;
}
[Category("Custom"),
Description("Specifies the highlight color.")]
public Color HighlightColor { get; set; }
protected override void OnSelectionChanged(EventArgs e)
{
base.OnSelectionChanged(e);
this.Invalidate();
}
private const int WM_PAINT = 15;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_PAINT)
{
var selectLength = this.SelectionLength;
var selectStart = this.SelectionStart;
this.Invalidate();
base.WndProc(ref m);
if (selectLength > 0) return; // Hides the highlight if the user is selecting something
using (Graphics g = Graphics.FromHwnd(this.Handle))
{
Brush b = new SolidBrush(Color.FromArgb(50, HighlightColor));
var line = this.GetLineFromCharIndex(selectStart);
var loc = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(line));
g.FillRectangle(b, new Rectangle(loc, new Size(this.Width, LineHeight)));
}
}
else
{
base.WndProc(ref m);
}
}
}
我们如何在渲染文本后面绘制这个高光? – user2320861
请有人可以帮我吗? http://stackoverflow.com/questions/23034423/c-sharp-adding-custom-richtextbox – user3354197
我们可以做些什么来突出特定的行与不同的颜色,光标定位线?在具体情况下,比如说,偶数行数必须以红色显示,奇数行以绿色显示。 – Kamlesh