Search code examples
.netvb.netgdi+system.drawing

Graphics Object in vb.net


I just started creating graphics in vb.net. I created a windows form and double clicked on it. I then got a method which was Form Load method. In this method i wrote the following code.

    Dim g As Graphics
    g = Me.CreateGraphics

    Dim pencolor As New Pen(Color.Red)
    g.DrawLine(pencolor, 10, 20, 100, 200)

I know that Graphics must be created in Paint event. But i am trying to display them in the Form Load Event. For some reason i don't see the output What could possibly be the problem..??


Solution

  • Don’t use CreateGraphicsever. I don’t think it actually has a legitimate use-case.

    Your problem is that you paint something on the form but it’s over-written as soon as the next redrawing of the form is triggered because graphics you create that way are not persisted.

    You essentially have to use the Paint event (or the OnPaint method) for drawing, there’s no way around this. If you want to trigger a redraw in Form_Load you can simply call Me.Invalidate (but I think that should be redundant).

    Inside the OnPaint method (or the Paint event), use the Graphics object provided in the parameters:

    Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
        MyBase.OnPaint(e) ' First, let the base class do its thing
    
        Dim g = e.Graphics
    
        Using p As New Pen(Color.Red)
            g.DrawLine(…)
        End Using
    End Sub 
    

    (Notice that Pen is a disposable resource and as such you should wrap it in a Using block.)