如何移动一个物体形成角落然后停止?

时间:2014-12-12 16:05:31

标签: vb.net visual-studio-2010 visual-studio-2013

此代码应该做的是将对象移动到表单的选定角落,通过单击它,然后它应该在到达目的地时停止,而不使用(。位置)属性。

但是在我的代码中,它不断超越表单边框。

 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 Button1.Left = (Me.Width - Button1.Width) Then
             Timer1.Enabled = False
           Else
               Button1.Left += 10
               Button1.Top -= 10
           End If

        End Sub

1 个答案:

答案 0 :(得分:1)

你递增10而不是1,所以很可能你传递Me.Width - Button1.Width而没有完全等于它。

检查您是否大于目标,并使用Me.ClientRectangle.Width代替Me.Width

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Dim RightReached As Boolean = False
    If Button1.Left >= (Me.ClientRectangle.Width - Button1.Width) Then
        Button1.Left = Me.ClientRectangle.Width - Button1.Width
        RightReached = True
    Else
        Button1.Left += 10
    End If

    Dim TopReached As Boolean = False
    If Button1.Top <= 0 Then
        Button1.Top = 0
        TopReached = True
    Else
        Button1.Top -= 10
    End If

    If RightReached AndAlso TopReached Then
        Timer1.Stop()
    End If
End Sub