繁体   English   中英

C# RichTextBox 高亮线

[英]C# RichTextBox Highlight Line

我已经上传了我想要实现的图像...在此处输入图片说明

如您所见,我想突出显示我单击的行 [并在 _textchanged 事件上更新它! 有没有可能用任何颜色来做到这一点......不必是黄色。 我已经搜索了很多,但我无法理解如何获得起始长度和结束长度以及所有这些。

它让我很困惑,我不明白,需要一些帮助。 感谢您在此线程中提供的所有帮助。 它也是窗口形式。 我正在制作一个记事本应用程序,如记事本++或其他一些记事本应用程序...... .NET Windows Form C# RichTextBox

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM