Home > other >  How do I access a method from another form
How do I access a method from another form

Time:11-19

I'm doing a projectile motion project and I want a live animation to play when you press a button. The button opens another form and to get the projectile to move I need to call a method from the first form

Public Class Projectile
    Public Sub UpdatePosition()
        Left = Left   10
    End Sub
End Class

This is the code from the first form

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        For Each control As Control In Controls
            If TypeOf control Is Projectile Then

            End If
        Next
    End Sub

and this where I want to call UpdatePosistion to.

How can I do this?

CodePudding user response:

We need to cast the control variable in the For Each loop and If block to a Projectile variable. We can simplify this using the OfType(Of T) method:

For Each control As Projectile In Controls.OfType(Of Projectile)()
    control.UpdatePosition()
Next

The OfType() call handles both the cast and If check for us.

CodePudding user response:

Your class needs Inherits Control or it will not be found in the Controls collection.

Cast the control to the type with the UpdatePosition method.

Public Class Projectile
    Inherits Control
    Public Sub UpdatePosition()
        Left = Left   10
    End Sub
End Class

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    For Each control As Control In Controls
        If TypeOf control Is Projectile Then
            DirectCast(control, Projectile).UpdatePosition()
        End If
    Next
End Sub
  • Related