在程序中有时可能需要控件能在程序窗口拖动,这时就需要拖动控件的代码。我们可以用控件的MouseDown,MouseUp事件实现控件的拖动。例如图1,我们怎么实现窗口中控件PictureBox1的拖动那?
![这里写图片描述](https://img-blog.csdn.net/2018072813552824?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3VzZXJs/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
图中我们已经在窗体上放了一个控件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 + (Y - yPos)
End If
End Sub
这下我们就可以实现运行时窗体上控件的拖动了。图中我们在Picture1上按下鼠标左键,然后移动一定距离,把控件Picture1移动到了另一位置。
![这里写图片描述](https://img-blog.csdn.net/20180728140116895?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3VzZXJs/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
需要注意的是,使用MouseDown,MouseUp,就不要设置控件的DropMode为属性为1-Automatic。