Search code examples
.netvb.netvisual-studio-2010system.drawingdrawstring

DrawString only works in top-left part of form vb.net


Here is my code

Public Class Form1

Public MyFormObject As Graphics = Me.CreateGraphics
Public objFont = New System.Drawing.Font("arial", 20)
Public a, b As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Randomize()
    For i = 1 To 10
        a = CInt(Int(Rnd() * Me.Width))
        b = CInt(Int(Rnd() * Me.Height))
        MyFormObject.DrawString("text", objFont, System.Drawing.Brushes.Black, a, b)
    Next
End Sub
End Class

As you can see, I have one button that draws the string "text" randomly in the form 10 times. My problem is that it will ONLY draw the string in the upper-left portion of the form, roughly 260x260 starting at 0,0. It literally cuts off the text if it goes beyond. Why is this? Shouldn't it work for the entire form?


Solution

  • You will need to move the CreateGraphics inside your sub. From Microsoft's documentation:

    The Graphics object that you retrieve through the CreateGraphics method should not normally be retained after the current Windows message has been processed, because anything painted with that object will be erased with the next WM_PAINT message. Therefore you cannot cache the Graphics object for reuse.

    Public Class Form1
    
        Public objFont = New System.Drawing.Font("arial", 20)
        Public a, b As Integer
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            Dim MyFormObject As Graphics = Me.CreateGraphics
    
            Randomize()
            For i = 1 To 10
                a = CInt(Int(Rnd() * Me.Width))
                b = CInt(Int(Rnd() * Me.Height))
                MyFormObject.DrawString("text", objFont, System.Drawing.Brushes.Black, a, b)
            Next
    
            MyFormObject.Dispose
    
        End Sub
    
    End Class