用定时器移动 PictureBox

Moving PictureBox with Timer

我想创建一个程序,当我单击一个按钮时,与表单具有相同宽度和高度的 PictureBox 向下移动,但我希望 Timer 在 PictureBox 离开后立即停止 frame/form.当我单击另一个 Button 时,PictureBox 会向上移动,但当它位于窗体的中心时会停止,基本上与向下移动之前的位置相同。如果有帮助,表单的大小为 700、1000。这是我的代码:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Timer1.Enabled = True
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y + 9)
    If (PictureBox1.Location = New Point(700, 1100)) Then
    Timer1.Enabled = False
    End If

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Timer2.Enabled = True
End Sub

Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
    PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y - 9)
    If (PictureBox1.Location = New Point((Me.Width / 700) - (PictureBox1.Width / 700), (Me.Height / 1000) - (PictureBox1.Height / 1000))) Then
        Timer2.Enabled = False
    End If
End Sub

让我们假设您的 PictureBox 从包含控件(即窗体、面板或其他)的左上角开始。这是Point(0,0)

在此事件处理程序中...

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y + 9)
    If (PictureBox1.Location = New Point(700, 1100)) Then
    Timer1.Enabled = False
    End If

End Sub

...您正在检查 PictureBox1 的左上角是否位于位置 700,1100,而不是检查它是否位于 0,1100。此外,由于您在每个计时器滴答声中添加 + 9,因此它永远不会位于恰好 1100 的 Y 位置。

然后在这次活动中...

Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
    PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y - 9)
    If (PictureBox1.Location = New Point((Me.Width / 700) - (PictureBox1.Width / 700), (Me.Height / 1000) - (PictureBox1.Height / 1000))) Then
        Timer2.Enabled = False
    End If
End Sub

您想检查 PictureBox1.Location 现在是否为 0,0(起始位置)而不是您正在做的所有位置数学运算。

这是您的代码的清理版本。请注意,它首先检查 PictureBox 的位置,仅在必要时才移动它。

Private Const INCREMENT As Integer = 9

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Timer1.Enabled = True

End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

    If PictureBox1.Location.Y >= 1100 Then

        Timer1.Enabled = False

    Else

        PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y + INCREMENT)

    End If

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

    Timer2.Enabled = True

End Sub

Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick

    If PictureBox1.Location.Y <= 0 Then

        Timer2.Enabled = False

    Else

        PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y - INCREMENT)

    End If

End Sub