2014-04-12 121 views
2
线

我已上载的是什么,我想才达到一个图像... enter image description hereC#RichTextBox的突出

因此,大家可以看到,我想强调这一行我点击[和更新上_textchanged事件! 是否有任何可能的方式做到这一点在任何颜色...不一定是黄色的。我已经搜索了很多,但我不明白如何获得起始长度和结束长度以及所有这些。

它困惑了我很多,我不明白,需要一些帮助。 感谢您在此主题中提供的所有帮助。也是Windows窗体。我做一个记事本应用程序,如记事本++或其他一些记事本应用程序... .NET Windows窗体C#RichTextBox

回答

3

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

我们如何在渲染文本后面绘制这个高光? – user2320861

+0

请有人可以帮我吗? http://stackoverflow.com/questions/23034423/c-sharp-adding-custom-richtextbox – user3354197

+0

我们可以做些什么来突出特定的行与不同的颜色,光标定位线?在具体情况下,比如说,偶数行数必须以红色显示,奇数行以绿色显示。 – Kamlesh