辉克's Blog

创造机会的人是勇者;等待机会的人是愚者

vb移动没有标题栏的窗口

方法1:API(模拟鼠标操作)

首先加入以下 API 声明以及相关常数(在标准模块中用 Public;在类模块或窗体中用 Private):
Public/Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Public/Private Declare Function ReleaseCapture Lib "user32" () As Long
Public/Private Const WM_NCLBUTTONDOWN = &HA1 '表示在非客户区(标题栏、边框)按下鼠标左键
Public/Private Const HTCAPTION = 2 '表示鼠标击中了窗口的标题栏

然后在某个控件的 MouseDown 事件的处理程序中加入:
ReleaseCapture
'在 VB 内部都会自动使用 SetCapture(API)来捕捉鼠标事件
'因此先使用 ReleaseCapture 使 SetCapture 失效
SendMessage Me.hwnd, WM_NCLBUTTONDOWN, HTCAPTION, ByVal 0&
'然后向窗口发送鼠标在标题栏被按下的消息

例如:
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
ReleaseCapture
SendMessage Me.hwnd, WM_NCLBUTTONDOWN, HTCAPTION, ByVal 0&
End Sub

方法2:VB
以通过窗口上的一个按钮(Command1)来拖动窗口为例,代码如下:
Dim LastX As Single, LastY As Single, IsMoving As Boolean

Private Sub Command1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
If Button = vbLeftButton Then
LastX = X
LastY = Y
IsMoving = True
End If
End Sub

Private Sub Command1_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
If IsMoving Then
Me.Move Me.Left + (X – LastX), Me.Top + (Y – LastY)
End If
End Sub

Private Sub Command1_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
IsMoving = False
End Sub

方法1较为简便,但确实有效;
方法2的操控性较强,您可以通过程序来干预拖动过程(例如防止窗口被拖离屏幕)。

发表评论

电子邮件地址不会被公开。 必填项已用*标注