VB.NET如何使用类似的过程控制多个控件



我使用以下代码:

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新手,我甚至不知道这是我能做的事情,还是我在未来会被大量的复制/粘贴所困扰?

为表单中的每个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

最新更新