您需要創建自己的控件從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