I have a function that is being called every 500 milliseconds and that should erase the old drawing contained in the PictureBox and replace it by a new one
public override void onUpdate()
{
pictureBox.Image = null;
Graphics g = pictureBox.CreateGraphics();
Pen p = new Pen(System.Drawing.Color.Blue, 3);
Random rnd = new Random();
int randomInt = rnd.Next(0, 11);
g.DrawEllipse(p, new Rectangle(new Point(0,randomInt), pictureBox.Size));
p.Dispose();
g.Dispose();
return;
}
does not work(nothing appears on the screen), except when debugging.. whereas when I do this:
public override void onUpdate()
{
Graphics g = pictureBox.CreateGraphics();
Pen p = new Pen(System.Drawing.Color.Blue, 3);
Random rnd = new Random();
int randomInt = rnd.Next(0, 11);
g.DrawEllipse(p, new Rectangle(new Point(0,randomInt), pictureBox.Size));
p.Dispose();
g.Dispose();
System.Threading.Thread.Sleep(5000);
pictureBox.Image = null;
return;
}
the circle is being drawn every 5 seconds after which it disappears for 500ms
the second one is logic to me, but I do not understand why the first one doesn't work the way I want.. If I remove the "pictureBox.Image = null;" line, the old circle isn't being removed.
What can I do, to redraw the circle everytime onUpdate() is being called, and let it stay so until the next time it is being called?
Winforms GDI+ been a while...
new approach: make a usercontrol and enter the code below inside, then replace your picture box with the new control (you have to compile it once so that it is in your toolbox) and your code and just call the UpdateCircle Method of the new control:
public partial class CircleControl : UserControl
{
private Random rnd = new Random();
Pen p = new Pen(Color.Blue, 3);
public CircleControl()
{
InitializeComponent();
this.Paint += CircleControl_Paint;
}
public void UpdateCircle()
{
this.Invalidate();
}
void CircleControl_Paint(object sender, PaintEventArgs e)
{
e.Graphics.Clear(Color.White);
int randomInt = rnd.Next(0, 11);
e.Graphics.DrawEllipse(p, new Rectangle(new Point(0, randomInt), this.Size));
}
}