拖动无标题栏的窗口

很多时候编程都需要拖动无标题栏的窗口,我不想每次都去查 API 浏览器和 MSDN,所以就把代码放到博客上。其实 Form(Form1)改为任何具有 hWnd 属性的控件都可以。

Option Explicit

Private Type POINTAPI
    X As Long
    Y As Long
End Type

Private Declare Function SetCapture Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function ReleaseCapture Lib "user32" () As Long
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long

Dim Pt As POINTAPI
Private bM As Boolean, oldX As Long, oldY As Long

Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
    SetCapture Form1.hwnd
    bM = True
    GetCursorPos Pt
    oldX = Pt.X
    oldY = Pt.Y
End Sub

Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
    If Not bM Then Exit Sub
    GetCursorPos Pt
    Form1.Left = Form1.Left + (Pt.X - oldX) * Screen.TwipsPerPixelX
    Form1.Top = Form1.Top + (Pt.Y - oldY) * Screen.TwipsPerPixelY
    oldX = Pt.X
    oldY = Pt.Y
End Sub

Private Sub Form_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
    ReleaseCapture
    bM = False
End Sub

这样就可以了。随意拖动没有标题栏的窗口。

但是,更好的方法是使用 SendMessage 发送 WM_NCLEFTBUTTONDOWN 消息,采用 HTCAPTION。

分享到 评论