开发者

Drawing on a panel in the constructor of a form

开发者 https://www.devze.com 2023-01-07 11:43 出处:网络
I have the following sample code, which I expect to color the panel on the form red as soon as i开发者_JAVA技巧t loads:

I have the following sample code, which I expect to color the panel on the form red as soon as i开发者_JAVA技巧t 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?


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消