Hello,I have a function that draws a rectangle on a form (different widths and heights)

public void drawRectangle()
{
    Graphics g = pictureBox1.CreateGraphics();
    Rectangle rect = new Rectangle(50, 50, 60, 50);
    g.DrawRectangle(Pens.Black, 10, 10, 10, 10);
}

I have a picturebox called picturebox1 but how would I get the rectangle to display in the picture box?

Thanks =)

Recommended Answers

All 5 Replies

Other than you create a rectangle object then don't use it to draw the rectangle, I don't see a problem with the code. Are you having some issue?

Hey, it's not even creating the rectangle..

The rectangle you've asked it to create is very small, only 10 pixels on a side. Maybe you just don't notice it.

This very code draws a nice black rectangle on my computer.

Drop a PictureBox on your from and set up its Paint event handler like this

private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            Pen bluePen = new Pen(Color.Blue, 2);
            g.DrawRectangle(bluePen, 10, 10, 50, 20);        }

It will draw a nice blue rectangle with a blue pen of two pixels wide.

@Phil++
Did this answer answered your question, or not?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.