2016-05-26 3 views
1

カスタムコントロールを作成してフォームにバインドしました。コントロールにグラフィックステキストを描画し、Formに追加しました。しかし、それはフォームを表示していませんでした。これは私のコードです。DrawStringのカスタムコントロールのテキストがwinformsに表示されないC#

// Form1の

public Form1() 
     { 
      InitializeComponent();   

      DrawTextImage call = new DrawTextImage(); 
      call.Text = "TextControl"; 
      call.Name = "TextContrl"; 
      Size siz = new Size(200, 100); 
      call.Location = new Point(0, 0); 
      call.Visible = true; 
      call.Size = siz; 
      call.DrawBox(new PaintEventArgs(call.CreateGraphics(), call.ClientRectangle), siz); 
      this.Controls.Add(call); 
     } 

にこの上の任意のヘルプをロード//

public class DrawTextImage : Control 
    { 

     public void DrawBox(PaintEventArgs e, Size size) 
     { 
      e.Graphics.Clear(Color.White); 
      int a = 0; 
      SolidBrush textColor = new SolidBrush(Color.Black); 
      using (SolidBrush brush = new SolidBrush(Color.Red)) 
      { 

       e.Graphics.FillRectangle(brush, new Rectangle(a, a, size.Width, size.Height)); 
       e.Graphics.DrawString("Text", Font, textColor, new PointF(50, 50)); 
      } 
     } 
    } 

カスタムコントロールを作成して、私が間違って何をしましたか?

+1

現在、コントロールはテキストを1回だけ表示します。描画パートは、コントロールの 'OnPaint'メソッドの中で行うべきです。これは、ビデオゲームのメインループのような反復的な方法です。 – raidensan

+0

'control.CreateGraphics'を使用しないでください! 'Graphics'オブジェクトをキャッシュしないでください! 'Graphics.g = Graphics.FromImage(bmp)'を使って 'Bitmap bmp'に描画するか、' e.Graphics'パラメータを使ってコントロールの 'Paint'イベントに描画します。 – TaW

答えて

4

手動で呼び出す必要があるカスタムメソッドではなく、コントロール自身のPaintイベントを使用する必要があります。

public class DrawTextImage : Control 
{ 
    protected override void OnPaint(PaintEventArgs e) 
    { 
     e.Graphics.Clear(Color.White); 
     int a = 0; 
     SolidBrush textColor = new SolidBrush(Color.Black); 
     using (SolidBrush brush = new SolidBrush(Color.Red)) 
     { 
      //Note: here you might want to replace the Size parameter with e.Bounds 
      e.Graphics.FillRectangle(brush, new Rectangle(a, a, Size.Width, Size.Height)); 
      e.Graphics.DrawString("Text", Font, textColor, new PointF(50, 50)); 
     } 
    } 
} 

DrawBoxへの電話を削除する必要はありません。

Paintイベントは、コントロールサーフェスの再描画が必要な場合は常に自動的に起動されます。コントロールのInvalidate()またはRefresh()メソッドを使用して、コード内でこれを自分自身で求めることができます。

関連する問題