vb中怎样拖动控件

2024-11-30 13:21:04
推荐回答(1个)
回答1:

‘拖动command1的例子
Option Explicit
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Private Declare Function ScreenToClient Lib "user32" (ByVal hwnd As Long, lpPoint As POINTAPI) As Long
Private Type POINTAPI
x1 As Long
y1 As Long
End Type
Dim cmdX1 As Integer
Dim cmdY1 As Integer
Private Sub Command1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
Dim P As POINTAPI
If Button = vbLeftButton Then
GetCursorPos P '获取鼠标在屏幕中的位置
ScreenToClient Me.hwnd, P '将现有坐标0,0转换为本窗体的坐标
cmdX1 = Command1.Left - P.x1 * Screen.TwipsPerPixelX
cmdY1 = Command1.Top - P.y1 * Screen.TwipsPerPixelY
End If
End Sub
Private Sub Command1_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
Dim P As POINTAPI
Dim t As Boolean
If Button = vbLeftButton Then
GetCursorPos P '获取鼠标在屏幕中的位置
ScreenToClient Me.hwnd, P '将现有坐标0,0转换为本窗体的坐标
t = P.x1 >= 0 And P.y1 >= 0 And P.x1 < Me.Width / Screen.TwipsPerPixelX And P.y1 <= Me.Height / Screen.TwipsPerPixelY
If t Then
Command1.Left = P.x1 * Screen.TwipsPerPixelX + cmdX1
Command1.Top = P.y1 * Screen.TwipsPerPixelY + cmdY1
End If
End If
End Sub