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?
You can achieve this overriding the OnLoad event of Form, also you can reuse the PaintEvent parameter.
Edit: added using statement for disposing resources