带定时器的Moving PictureBox



我想创建一个程序,其中当我单击按钮时,PictureBox具有与表单相同的宽度和高度向下移动,但我希望计时器在PictureBox离开框架/表单后立即停止。当我点击另一个按钮时,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。位置现在是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

最新更新