0

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?

Ivan Spajić
  • 159
  • 3
  • 5
  • 14

2 Answers2

1

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

4D1C70
  • 490
  • 3
  • 10
  • 2
    You should properly show how to dispose the disposables. – Enigmativity Oct 12 '17 at 00:15
  • You likely will want to call `base.OnPaint(e)` first instead of last, or else the form may draw over whatever you just painted. – Scott Chamberlain Oct 12 '17 at 13:31
  • 1
    Thank you for your contribution, however this unfortunately didn't do it for me. I found the answer in a very similar question to mine, so I marked this question as a duplicate. You are still right about having to dispose the respective objects. – Ivan Spajić Oct 12 '17 at 16:38
-1

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.

0014
  • 893
  • 4
  • 13
  • 40
  • 1
    I tried this, and it does not work for me. I'm able to get a print confirming that I'm hitting the correct method delegated by the event, however upon calling my Draw() method, nothing happens. – Ivan Spajić Oct 12 '17 at 16:06