Painting with System.Drawing.Graphics on form load

3.2k Views Asked by At

I'm trying to draw a rectangle using System.Drawing.Graphics in C# Windows Forms, but I cannot seem to get it to work without using a button click event.

Searching online uncovered that I must use either the Paint or the Shown event within the form itself, however my attempts were unsuccessful.

I would like to run my Draw() method upon loading the form and its components.

public Form1()
{
    InitializeComponent();
    Draw(); //doesn't work
}

private void Draw()
{
    Graphics g = pictureBox.CreateGraphics();
    g.Clear(Color.White);
    Pen p = new Pen(Color.Black, 1);
    g.DrawRectangle(p, 0, 0, 50, 50);
}

private void ApproximateButton_Click(object sender, EventArgs e)
{
    Draw(); //works
}

What is the correct way of achieving this?

2

There are 2 best solutions below

3
On

You can achieve this overriding the OnLoad event of Form, also you can reuse the PaintEvent parameter.

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    using (Graphics g = e.Graphics)
    {
        g.Clear(Color.White);
        using (Pen p = new Pen(Color.Black, 1))
        {
            g.DrawRectangle(p, 0, 0, 50, 50);
        }
    }
}

Edit: added using statement for disposing resources

1
On

You also should be fine placing your function under Form1's Load event.

After subscribing for the Load event try this;

public Form1()
{
    InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
    Draw();
}

private void Draw()
{
    Graphics g = pictureBox.CreateGraphics();
    g.Clear(Color.White);
    Pen p = new Pen(Color.Black, 1);
    g.DrawRectangle(p, 0, 0, 50, 50);
}

Load event is called after the constructor. Your form elements are being created in the constructor therefore you are having some problems trying to use them in the same function.