我正在使用以下代码:
Private Sub lblTest_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles lblTest.MouseDown
startx = MousePosition.X
starty = MousePosition.Y
mdown = True
valx = False
valy = False
End Sub
Private Sub Main_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
End Sub
Private Sub lblTest_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles lblTest.MouseMove
Dim endx As Integer
Dim endy As Integer
'Check if mouse=down
If mdown = True Then
endx = (MousePosition.X - Me.Left)
endy = (MousePosition.Y - Me.Top)
If valy = False Then
starty = endy - sender.top
valy = True
End If
If valx = False Then
startx = endx - sender.left
valx = True
End If
sender.left = endx - startx
sender.top = endy - starty
End If
End Sub
Private Sub lblTest_MouseUp(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles lblTest.MouseUp
mdown = False
valx = False
valy = False
End Sub
这样做是允许我在运行时使用鼠标移动标签。我想做的是用相似的代码移动多个标签,但是显然我不想为每个标签控件编写一个过程。那就是我想将lblTest移到lblTest(1 + n)。我计划移动的标签数量将是不确定的(由于过于枯燥的原因,无法详细说明)。
太多的vb新手甚至不知道这是我可以做的事情,还是将来我只是坚持使用大量复制/粘贴?
答案 0 :(得分:0)
为表单中的每个Label控件循环,并向它们添加相同的事件处理程序:
示例:
For Each lab As Label In Controls
If (TypeOf lab Is Label) Then
AddHandler lab.MouseMove, AddressOf Your_MouseMove
AddHandler lab.MouseDown, AddressOf Your_MouseDown
AddHandler lab.MouseUp, AddressOf Your_MouseUp
End If
Next
Private Sub Your_MouseUp(sender As Object, e As MouseEventArgs)
' Mouse up code
End Sub
Private Sub Your_MouseDown(sender As Object, e As MouseEventArgs)
'Mouse Down code
End Sub
Private Sub Your_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs)
Dim endx As Integer
Dim endy As Integer
'Check if mouse=down
If mdown = True Then
endx = (MousePosition.X - Me.Left)
endy = (MousePosition.Y - Me.Top)
If valy = False Then
starty = endy - sender.top
valy = True
End If
If valx = False Then
startx = endx - sender.left
valx = True
End If
sender.left = endx - startx
sender.top = endy - starty
End If
End Sub