VB.NET Draw On Form Outside form1_paint() Function

In Visual Studio VB.net Form project you can draw on the form simple by doing this is the Form1_Paint function and then using the e As System.Windows.Forms.PaintEventArgs like this:

Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
   e.DrawImage(Image.FromFile("background.png"), New PointF(0, 0)) 
End Sub

To draw on the form outside of the form1_paint, say a button click you can use System.Drawing.Graphics like this:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
   Dim myPen As New System.Drawing.Pen(System.Drawing.Color.Red)
   Dim g As System.Drawing.Graphics
   g = Me.CreateGraphics()
   ' Draw image
   g.DrawImage(Image.FromFile("background.png"), New PointF(0, 0))
   ' Draw a line
   g.DrawLine(myPen, 0, 0, 200, 200)
End Sub

Notes “Dim g As System.Drawing.Graphics” and “g = Me.CreateGraphics()” is what let us draw on the form.

Posted in Tips and Tricks, Windows Tagged with: , ,