简体   繁体   English

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

[英]The class inherited from Control doesnt show on the form

i have a class written in c# inherited from Control like below. 我有一个用C#编写的类继承自Control,如下所示。

    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);
    }        
   }

And from my main form i create an object of this class. 从我的主要形式,我创建了这个类的对象。 and add thid object to the form, like below. 并将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);
}

but it doesnt appear on the form. 但它没有出现在表格上。 What is the problem. 问题是什么。
Thanks. 谢谢。

You should not draw anything in a class constructor. 你不应该在类构造函数中绘制任何东西。 You should override OnPaint method and draw all of your custom graphics here. 您应该覆盖OnPaint方法并在此处绘制所有自定义图形。

You can write someting like this: 你可以写这样的东西:

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);
    }       
}

The recepient code: 接收代码:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM