title: How to dynamically create an overlay over a VB.Net PictureBox
body: <p>I have a VB.Net PictureBox <code>floorPlanImage</code> on a form <code>form1</code>.</p>
  
  <p>I load a picture into the picturebox:</p>
  
  <pre><code>    floorPlanImage.image = my.resources.ResourceManager.GetObject("level8") 'this is actually dynamic, and this part works
  </code></pre>
  
  <p>I am trying to create an overlay to highlight a region of the image:</p>
  
  <pre><code>    Public Sub highlightPrintArea(ByVal x1 As Integer, ByVal y1 As Integer, ByVal x2 As Integer, ByVal y2 As Integer)
      '**** DOES NOT WORK
      Dim g As Graphics = Me.CreateGraphics
      Dim r As Rectangle = New Rectangle(x1, y1, x2 - x1, y2 - y1) 'these are args passed in to the function
      Dim pen As Pen = New Pen(Color.FromArgb(128, 32, 100, 200), 1) 'semi-transparent
      Dim b As Brush = New SolidBrush(pen.Color)
  
      g.FillRectangle(b, r)
      end sub
  </code></pre>
  
  <p>I need to do this dynamically at runtime, say, on button click. The above function does not seem to draw the rectangle.</p>
  
  <p>However, if I have a function that <code>Handles floorPlanImage.Paint</code> like follows, then the rectangle is drawn as I expect it to:</p>
  
  <pre><code>Private Sub floorPlanImage_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles floorPlanImage.Paint
      '**** Works, but does not suit my workflow
      Dim g As Graphics = e.Graphics
      Dim r As Rectangle = New Rectangle(100, 100, 100, 100)
      Dim pen As Pen = New Pen(Color.FromArgb(128, 32, 100, 200), 1)
      Dim b As Brush = New SolidBrush(pen.Color)
  
      g.FillRectangle(b, r)
  End Sub
  </code></pre>
  
  <p><strong>The Question (finally)</strong></p>
  
  <p>How can I modify my onclick function to correctly overlay the rectangle over my PictureBox?</p>