2014-06-25 49 views
-1

我在我加入一個RichTextBox設計師創造了一個新的UserControl。然後,我的確在UserControl構造:我如何在richTextBox1上繪圖?

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Drawing; 
using System.Data; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace ScrollLabelTest 
{ 
    public partial class ScrollText : UserControl 
    { 
     Font drawFonts1 = new Font("Arial", 20, FontStyle.Bold, GraphicsUnit.Pixel); 
     Point pt = new Point(50, 50); 

     public ScrollText() 
     { 
      InitializeComponent(); 

      System.Drawing.Font f = new System.Drawing.Font("hi",5); 
      Graphics e = richTextBox1.CreateGraphics(); 
      e.DrawString("hello",drawFonts1,new SolidBrush(Color.Red),pt); 
      this.Invalidate(); 
     } 
    } 
} 

於是我拖着新UserControlform1設計師,但它是空的。我沒看到「你好」這個詞。

+0

你已經安裝的字體被稱爲 「喜」?哦,等等,你沒有使用'f'。 – gunr2171

+1

只要你'Invalidate',你的'Form'重新繪製本身,包括你的'RickTextBox'控制(我猜),反過來'RickTextBox'控制重繪自己和除去繪製了它額外的東西的東西。 – sallushan

+0

刪除Invalidate沒有幫助。試圖使richTextBox1.Invalidate在所有情況下它沒有繪製文本。有或沒有無效。 – user3756594

回答

0

一種方法是延長RichTextBox控制和OnPaint方法實現您的自定義繪製。但通常,所以你必須通過hookingWndProc方法手動調用方法RichTextBox控制不調用OnPaint方法。

例子:

class ExtendedRTB : System.Windows.Forms.RichTextBox 
{ 
    // this piece of code was taken from pgfearo's answer 
    // ------------------------------------------ 
    // https://stackoverflow.com/questions/5041348/richtextbox-and-userpaint 
    private const int WM_PAINT = 15; 
    protected override void WndProc(ref System.Windows.Forms.Message m) 
    { 
     base.WndProc(ref m); 
     if (m.Msg == WM_PAINT) 
     { 
      // raise the paint event 
      using (Graphics graphic = base.CreateGraphics()) 
       OnPaint(new PaintEventArgs(graphic, 
       base.ClientRectangle)); 
     } 

    } 
    // -------------------------------------------------------- 

    protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) 
    { 
     base.OnPaint(e); 
     e.Graphics.DrawString("hello", this.Font, Brushes.Black, 0, 0); 
    } 
} 
+0

sallushan我想你的解決方案怪:當我在Form1設計師拖累Form 1設計圍繞着控制我看到的文字打招呼,但一旦我離開的地方,而不是拖動控制它我沒有看到控制上的白色背景顏色的問候文字。我用了一個breakpoitn,它已經進入了繪畫事件,但只有當我拖動usercontrol時纔會看到你好。 – user3756594

+0

sallushan我發現了這個問題。您的解決方案是在UserControl上繪製不在richTextBox上的字符串。我的richTextBox位於UserControl設計器上。也許我在這裏想念一些東西 – user3756594

+0

你可以在我更新的問題中看到我用截圖編輯它。 「你好」是在UserControl上繪製的,而不是在UserControl設計器的richTextBox1上繪製的! – user3756594