从Control继承的类不会在表单上显示

时间:2013-01-21 10:46:49

标签: c# winforms user-controls

我有一个用继承自Control的c#编写的类,如下所示。

    class MyImage:Control
    {
    private Bitmap bitmap;
    public MyImage(int width, int height)
    {
        this.Width = width;
        this.Height = height;
        bitmap = new Bitmap(width,height);
        Graphics gr = Graphics.FromImage(bitmap);
        gr.FillRectangle(Brushes.BlueViolet,0,0,width,height);
        this.CreateGraphics().DrawImage(bitmap,0,0);
    }        
   }

从我的主要表单中我创建了这个类的对象。并将thid对象添加到表单中,如下所示。

private void button1_Click(object sender, EventArgs e)
{
        MyImage m = new MyImage(100,100);
        m.Left = 100;
        m.Top = 100;
        this.Controls.Add(m);
}

但它没有出现在表格上。有什么问题。
感谢。

1 个答案:

答案 0 :(得分:7)

你不应该在类构造函数中绘制任何东西。您应该覆盖OnPaint方法并在此处绘制所有自定义图形。

你可以写这样的东西:

public partial class MyImage : Control
{
    public MyImage()
    {
        InitializeComponent();

        bitmap = new Lazy<Bitmap>(InitializeBitmap);    
    }

    private Lazy<Bitmap> bitmap;
    private Bitmap InitializeBitmap()
    {
        var myImage = new Bitmap(Width, Height);
        using(var gr = Graphics.FromImage(myImage))
        {
            gr.FillRectangle(Brushes.BlueViolet, 0, 0, Width, Height);
        }

        return myImage;
    }

    protected override void OnPaint(PaintEventArgs pe)
    {
        base.OnPaint(pe);

        pe.Graphics.DrawImage(bitmap.Value, 0, 0);
    }       
}

接收代码:

private void button1_Click(object sender, EventArgs e)
{
  var m = new MyImage(100,100)
  {
    Width = 100,
    Height = 100,
    Left = 100,
    Top = 100
  }

  Controls.Add(m);
}