动画按钮移动

时间:2017-08-03 15:27:56

标签: vb.net

我正在尝试在VB.Net中的Windows窗体上设置两个按钮的移动动画。表单从主窗体加载ShowDialog()。我有以下代码:

Private Sub MoveButtons(sender As Object, e As EventArgs) Handles picLogo.Click
    Dim SLoc As Point = btnSearch.Location
    Dim CLoc As Point = btnCancel.Location

    txtSearch.Enabled = False
    txtSearch.Visible = False
    btnSearch.Text = "Add"

    For idx As Integer = 1 To 36
        SLoc.Y -= 1
        btnSearch.Location = SLoc
        CLoc.Y -= 1
        btnCancel.Location = CLoc
        Thread.Sleep(5)
    Next
End Sub

我最初使用Top属性对其进行编码,但结果是相同的。 “取消”按钮按预期方式向上滑动,但“搜索/添加”按钮从底部向上消失,然后跳到正确的位置。无论是否更改按钮文本,都会发生这种情况。除了明显的LocationText属性外,两个按钮完全相同,但“取消”按钮的DialogResult设置为DialogResult.Cancel

Form screenshots

1 个答案:

答案 0 :(得分:1)

您没有随时为UI提供正确的更新。虽然Thread.Sleep(5)对于循环的时间安排至关重要,但它也使UI线程处于休眠状态。你不想这样做。

因此,一个简单但不知情的修复方法是将Application.DoEvents()置于循环中。这将允许UI自行更新。这应该使你的代码工作......

...
Application.DoEvents()
Thread.Sleep(5)

但如果你做了足够多的这类事情,你会发现你的UI速度变慢了。它会给应用程序带来不好的感觉。你永远不想让UI线程进入休眠状态。

你应该做的是从UI上取下所有非ui的东西。您可以创建一个线程并将其放在那里。但是,在线程内部,您需要Invoke任何UI调用回UI。这是

的方式
Private Sub MoveButtons(sender As Object, e As EventArgs) Handles picLogo.Click
    txtSearch.Enabled = False
    txtSearch.Visible = False
    btnSearch.Text = "Add"
    Dim moveThread As New System.Threading.Thread(AddressOf moveButtonsSub)
    moveThread.Start()
End Sub

Private Sub moveButtonsSub()
    Dim SLoc As Point = btnSearch.Location
    Dim CLoc As Point = btnCancel.Location
    For idx As Integer = 1 To 36
        SLoc.Y -= 1
        CLoc.Y -= 1
        Me.Invoke(
            Sub()
                btnSearch.Location = SLoc
                btnCancel.Location = CLoc
            End Sub)
        Thread.Sleep(5)
    Next
End Sub
相关问题