Djdoggy99
Djdoggy99

Reputation: 3

VB.net Graphics not drawing to screen

I am creating a hangman game and i cant get my dashes to draw on the screen.

Public Class Form1

Public lines() As String= IO.File.ReadAllLines("C:\Users\axfonath14\Desktop\words_alpha.txt")
Dim thisArray As String() = lines.ToArray
Public word As String = thisArray(CInt(Int((thisArray.Length * Rnd()) + 1)))
Public g As Graphics = Me.CreateGraphics()
Public dash As Image = My.Resources.dash 
Public x As Integer = 1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Label1.Text = word
    For Each c As Char In word
        x += 1
        g.DrawImage(dash, 125 + (100 * x), 100)
    Next
    Label2.Text = x
End Sub

End Class

when i run this code it runs through the loop and changes the label to the amount of letters but it just wont draw anything.

Upvotes: 0

Views: 908

Answers (2)

jmcilhinney
jmcilhinney

Reputation: 54417

Never, EVER call CreateGraphics. Lazy people do so without explanation in examples and tutorials but it is never appropriate in a real application. ALWAYS do your drawing in the Paint event handler of the control you want to draw on. In your case, get rid of that g field altogether, move your drawing code to the Paint event handler of the form and use the Graphics object that it provides:

Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
    For Each c As Char In word
        x += 1
        e.Graphics.DrawImage(dash, 125 + (100 * x), 100)
    Next
End Sub

That way, your drawing gets restored each time the form gets erased and repainted, which can be often and will be after the Load event handler completes.

If you want to change what gets drawn then you need to store the appropriate data in fields that can then be accessed from the Paint event handler. To force a repaint, call Invalidate on the form or control whose Paint event you're handling.

Upvotes: 5

Joel Coehoorn
Joel Coehoorn

Reputation: 415600

You're grabbing the graphics context before the form has initialized. Move your initialization code to the actual constructor, after the InitializeComponent() method is called.

Upvotes: 0

Related Questions