在程序中有时可能需要控件能在程序窗口拖动,这时就需要拖动控件的代码。我们可以用控件的MouseDown,MouseUp事件实现控件的拖动。例如图1,我们怎么实现窗口中控件PictureBox1的拖动那?

图中我们已经在窗体上放了一个控件Picture1,需要拖动的就是它,我们在上面加了一个Label来标注它的名字。
我门现在在窗体代码中定义两个变量xPos,yPos,并在Picture1的MouseDown,MouseUp中添加如下代码:
Dim xPos As Long
Dim yPos As Long
‘注意要使用MouseDown,MouseUp,就不要设置控件的DropMode为1
Private Sub Picture1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
If Button = 1 Then
xPos = X
yPos = Y
End If
End Sub
Private Sub Picture1_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
If Button = 1 Then
Picture1.Move Picture1.Left + (X - xPos), Picture1.Top