【问题标题】:C# RichTextBox Highlight LineC# RichTextBox 高亮线
【发布时间】:2014-04-12 13:13:56
【问题描述】:

我已经上传了一张我想要实现的图片...

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

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

【问题讨论】:

    标签: c#


    【解决方案1】:

    您需要创建自己的从 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);
             }
         }
     }
    

    【讨论】:

    • 我们如何在渲染文本后面绘制这个高亮?
    • 有人可以帮我吗? stackoverflow.com/questions/23034423/…
    • 我们可以用不同的颜色突出显示光标定位线以外的特定线吗?在特定情况下,例如偶数行必须以红色显示,奇数行以绿色显示。
    猜你喜欢
    • 1970-01-01
    • 2015-11-12
    • 2013-08-13
    • 2020-12-06
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多