views:

34

answers:

2

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?

+2  A: 

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.

Henk Holterman
Definitely in the Paint event
colithium
I tried the Shown event and it looks like it has the same problem. That is a good suggestion though to use a flag and then do the drawing in the Paint event, I'll look into that.
bde
A: 

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