我想創建一個程式,其中當我單擊按鈕時,與表單具有相同寬度和高度的 PictureBox 向下移動,但我希望 Timer 在 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
uj5u.com熱心網友回復:
讓我們假設您的 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/417826.html
標籤:
