namco
namco

Reputation: 6348

The class inherited from Control doesnt show on the form

i have a class written in c# inherited from Control like below.

    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.

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.

Upvotes: 4

Views: 113

Answers (1)

Viacheslav Smityukh
Viacheslav Smityukh

Reputation: 5843

You should not draw anything in a class constructor. You should override OnPaint method and draw all of your custom graphics here.

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

Upvotes: 7

Related Questions