Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing onto a picturebox in a Windows Form from a different class

Tags:

c#

winforms

In my code, I have a PictureBox with a background picture. I used to draw a rectangle over it using

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    Pen p = new Pen(Color.Turquoise, 2);
    Rectangle r = new Rectangle(600, 300, 5, 5);
    e.Graphics.DrawRectangle(p, r);
    p.Dispose();
}

Now, that I know I will need to do a lot of things with these rectangles and create them dynamically, I have created a class for them, with a constructor looking like this:

public MyRectangles(int x, int y)
{
    Pen p = new Pen(Color.Turquoise, 2);
    Rectangle r = new Rectangle(x, y, 5, 5);
    e.Graphics.DrawRectangle(p, r);
    p.Dispose();
}

The problem is, that the e in e.Graphics.DrawRectangle(p, r); does not exist here. It makes sense, I understand why, however, I dont know what to replace it with, to draw on the same picturebox again.

like image 988
Marek Buchtela Avatar asked Mar 08 '13 16:03

Marek Buchtela


1 Answers

Try passing the Graphics object:

public MyRectangles(Graphics g, int x, int y)
{
    Pen p = new Pen(Color.Turquoise, 2);
    Rectangle r = new Rectangle(x, y, 5, 5);
    g.DrawRectangle(p, r);
    p.Dispose();
}
like image 171
LarsTech Avatar answered Oct 27 '22 08:10

LarsTech