我在一个Form上画了一个Label(就一个Label),然后实现将其进行拖动(代码如下),也就是将其MouseDown,MouseUp,MouseMove等方法进行扩展。我的想法是将扩展后的Label控件做成一个新控件,这个新控件封装了MouseDown,MouseUp,MouseMove等方法,拉来就可以用,而不需为每个Label编写相应的代码。
怎么实现?请高手指教,谢谢!
'定义鼠标移动前的位置
Dim tx As Single
Dim ty As Single
'定义差值
Dim mx As Integer
Dim my As IntegerPrivate Sub Label1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
    If Button = vbLeftButton Then
        '鼠标当前的位置
        tx = X
        ty = Y
    End If
End Sub'鼠标松开
Private Sub Label1_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
    Me.MousePointer = vbDefault
End Sub
Private Sub Label1_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
    
    If Button = vbLeftButton Then
        mx = tx - X
        my = ty - Y
        With Label1
            .Left = .Left - mx
            .Top = .Top - my
        End With
    End If
End Sub

解决方案 »

  1.   

    扩展label类就可以,
    方法添加一个类
    '定义鼠标移动前的位置
    Public WithEvents Label1 As Label
    Dim tx As Single
    Dim ty As Single
    '定义差值
    Dim mx As Integer
    Dim my As IntegerPrivate Sub Label1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
        If Button = vbLeftButton Then
            '鼠标当前的位置
            tx = X
            ty = Y
        End If
    End Sub'鼠标松开
    Private Sub Label1_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
        
    End Sub
    Private Sub Label1_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
        
        If Button = vbLeftButton Then
            mx = tx - X
            my = ty - Y
            With Label1
                .Left = .Left - mx
                .Top = .Top - my
            End With
        End If
    End Sub在form中加入如下代码Private xx As New Class1
    Private Sub Form_Load()
        Set xx.Label1 = Label1
    End Sub