C#RichTextBox突出显示行

我上传了一张我想要的图片…… 在此处输入图像描述

所以你可以看到我想要突出显示我点击的行[并在_textchanged事件上更新它! 是否有任何可能的方式以任何颜色这样做…不必是黄色。 我搜索了很多,但我不明白如何获得起始长度和结束长度以及所有这些。

它让我很困惑,我不知道,并且需要一些帮助。 感谢您在此主题中提供的所有帮助。 也是windowsforms。 我正在制作记事本应用程序,如记事本++或其他一些记事本应用程序… .NET Windows Form C#RichTextBox

您需要创建自己的控件,该控件inheritance自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); } } }