WildCrustacean
WildCrustacean

Reputation: 5966

Drawing on a panel in the constructor of a form

I have the following sample code, which I expect to color the panel on the form red as soon as it loads:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        drawstuff();
    }

    public void drawstuff()
    {
        using (Graphics g = panel1.CreateGraphics())
        {
            g.Clear(Color.Red);
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        drawstuff();
    }
}

However, for some reason it doesn't draw on the panel when I call my drawstuff() function from the constructor like that. When I press the button to call drawstuff(), it works just fine.

Can anyone explain what is happening here?

Upvotes: 2

Views: 1004

Answers (2)

Paul
Paul

Reputation: 3306

Might be easier to create your own custom Panel and override OnPaint...

public class MyCustomPanel : Panel
{
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        e.Graphics.Clear(Color.Red);
    }
}

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273169

what is happening here?

You get ahead of the normal Erasing/Painting of the Form. It is drawn and then erased when the Forms shows (for the 1st time).

You could try the FormCreate event (I'm not entirely sure) but putting it in the Shown event should certainly work.

But be aware that the results of DrawStuff() will disappear when you Minimize/Restore or click other windows in front.

Consider using a state flag (DoDrawStuff()) and do the actual drawing in the panel1_Paint event.

Upvotes: 4

Related Questions