Move form control with Thread

Asked

Viewed 27 times

-1

I’m trying to make a little 2D game, in it when the character moves the walls also move in a way that looks like some kind of game, however using timers would be a bad idea because when I add too many walls (Picturebox) would be too slow the form, then the other option would be to create a Thread to separate the work, the code I use to move the walls are there.

    Private Scene As New Thread(AddressOf MoveWalls)

    Private Sub MoveWalls()
        For Each Wall As PictureBox In Controls.OfType(Of PictureBox)()
            If Not Wall.Tag = "Player" Then
                Wall.Location = New Point(Wall.Location.X + X2, Wall.Location.Y + Y2)
            End If
        Next
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Scene.Start()
    End Sub

OBS: The player is also a Picturebox so for Thread not to use as a wall I changed the Player Tag to Player

When I run the application nothing happens, but I added a label to test if it could change the value and in doing so appeared an error on the screen. Erro

I even tried the solution tip that he recommends but did not succeed. Link to recommended solution Can anyone tell me if it is possible to change the location of the walls using Thread? If yes I need help, if not some better idea?

  • Why didn’t you succeed by following the link you posted? It gives clear examples of what you should do.

  • I have a bit of experience in Vb.net, but in all this time I only touched twice with thread (counting on this one), I made up my code following this solution tip but I did not get result.

1 answer

0


You must use the method Invoke for your GUI update to occur on thread leading.

Example:

Public Sub InternalMoveWall(ByVal wall As Control, ByVal x As Int64, ByVal y As Int64)
    If wall.InvokeRequired Then
        Me.Invoke(Sub() InternalMoveWall(wall, x, y))

    Else
        wall.Location = New Point(wall.Location.X + x, wall.Location.Y + y)
    End If

End Sub

Private Sub MoveWalls()
    For Each Wall As PictureBox In Controls.OfType(Of PictureBox)()
        If Not Wall.Tag = "Player" Then
            InternalMoveWall(Wall, 100, 100)
        End If
    Next
End Sub

Browser other questions tagged

You are not signed in. Login or sign up in order to post.