I'm working on a windows forms application and when I'm using the System.Drawing.Graphics
on top of a picturebox the graphics either don't appear or appear only momentarily before disappearing.
This is the code that I'm using to set the picturebox (it's a simplified version and still exhibits the behavior)
private void showGraphic()
{
pictureBox1.Invalidate();
System.Drawing.Graphics graphics = this.pictureBox1.CreateGraphics();
SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(128, 0, 0, 255));
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(100,100, 50, 50);
graphics.FillEllipse(semiTransBrush, rect);
}
private void button1_Click(object sender, EventArgs e)
{
showGraphic();
}
The settings for the picturebox are just the default settings with a picture from a file declared in the properties pane.
I was able to solve this problem by using a timer which was started by the button and then executed the graphic drawing before stopping itself, however this seemed a terrible solution and I wanted to do this a better way, if one exists as that could result in lack of portability to older computers.
Thanks in advance
You need to register a handler for the PictureBox's Paint method and do your drawing in that method. (Note: use the Graphics object passed in via the PaintEventArgs parameter.) That will guarantee that any time the PictureBox gets redrawn, your drawing code will run as well. Otherwise, you're just drawing over the top of something that will get refreshed for any of a number of reasons.
Once you've registered for the Paint event, anytime you want to repaint, call Invalidate() on the PictureBox and your painting code will run. You can keep track of whether or not your overlay graphics should be drawn via a private boolean member variable.