1
votes

So I'm trying to create a new form, draw a rectangle and then have that rectangle shown on the form. I can't seem to get it to show. The form shows but the rectangle isnt drawn.

I have this so far:

private void btnLayout_Click(object sender, EventArgs e)
{
    Form form = new Form();
    form.Text = "Design";
    using (Graphics g = form.CreateGraphics())
    {
        Pen pen = new Pen(Color.Black, 2);
        Brush brush = new SolidBrush(Color.AliceBlue);
        g.DrawRectangle(pen, 100, 100, 100, 200);
        pen.Dispose();
    }
    form.Show();
}
3
How big is the form? Is it higher than 100px and wider than 100px? - Bozhidar Stoyneff
Fixed it, check my answer - Andrew Kilburn

3 Answers

2
votes

You should paint on your form in Paint event of the form, otherwise your painting will be disappear if something make your form repaint, for example a minimize and restore or moving another window above your window.

Example

private void button1_Click(object sender, EventArgs e)
{
    var f = new Form();
    f.Paint += (se, pe) =>
    {
        var r = new Rectangle(10, 10, 100, 100);
        pe.Graphics.FillRectangle(Brushes.AliceBlue, r);
        using (var pen = new Pen(Color.Black, 2))
            pe.Graphics.DrawRectangle(pen, r);
    };
    f.Show();
}

Note

  • You can use Brushes.AliceBlue instead of new SolidBrush(Color.AliceBlue)
  • If in any reason you created a new SolidBrush, don't forget to dispose it.
  • Create and use disposable objects in a using block. This way they automatically will dispose after they went out of scope at the end of using.
  • The statement f.Paint += (se, pe) =>{/*...*/} is equivalent to f.Paint += f_Paint; and then having such method void f_Paint(object sender, PaintEventArgs e) {/*...*/} .
0
votes

For some reason I couldn't add a rectangle on a form that wasn't shown yet but it works if you put the code after the form has been shown.

private void btnLayout_Click(object sender, EventArgs e)
        {
            Form form = new Form();

            form.Text = "Design";

            form.Show();

            using (Graphics g = form.CreateGraphics())
            {
                Pen pen = new Pen(Color.Black, 2);
                Brush brush = new SolidBrush(Color.AliceBlue);

                g.DrawRectangle(pen, 100, 100, 100, 200);

                pen.Dispose();
            }
}
0
votes

Show the form, then draw the rectangle.

ie: move the form.Show() call above:

using (Graphics g = form.CreateGraphics())