2014-04-12 53 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