2

I am trying to create a rectangle on a picturebox with randome size and location. Every time the user click on a button, the rectangle will be removed and the new one will be displayed.

Private Sub btnDraw_Click(sender As Object, e As EventArgs) Handles btnDraw.Click
  RandomBox()
End Sub

Public Sub RandomBox()
  Dim r As New Rectangle(CInt(Rnd() * picGene.Width), CInt(Rnd() * picGene.Height), 20 + Rnd() * 50, 10 + Rnd() * 50)
  Dim g As System.Drawing.Graphics
  g = picGene.CreateGraphics()
  g.FillRectangle(Brushes.Blue, r)
End Sub

It always keeps the rectangles drawn previously so I tried to place the picGene.Invalide() before or after the code block. It removes the old rectangle but it does not draw the new rectangle.

Public Sub RandomBox()
  picGene.Invalidate()
  Dim r As New Rectangle(CInt(Rnd() * picGene.Width), CInt(Rnd() * picGene.Height), 20 + Rnd() * 50, 10 + Rnd() * 50)
  Dim g As System.Drawing.Graphics
  g = picGene.CreateGraphics()
  g.FillRectangle(Brushes.Blue, r)
  'picGene.Invalidate()
End Sub

Any idea?

Thanks

1 Answers1

1

Store a Rectangle in memory and just change that one with each click and paint it in the paint event. The Random class is a better choice these days for random generated values.

Private rect As New Rectangle

Private Sub btnDraw_Click(sender As Object, e As EventArgs) Handles btnDraw.Click
  Static rnd As New Random 
  rect = New Rectangle(rnd.Next(picGene.Width), rnd.Next(picGene.Height), 20 + rnd.Next({somevalue}) * 50, 10 + rnd.Next({someValue}) * 50)
  pb.Refresh() 'redraw the rectangle
End Sub

Private Sub picGene_Paint(sender As Object, e As PaintEventArgs) Handles picGene.Paint
  e.Graphics.DrawRectangle(Pens.Black, rect)
End Sub
OneFineDay
  • 9,004
  • 3
  • 26
  • 37