Visual Basic.NET 7.x (2002/03)Visual Basic 10Visual Basic 9 (2008)Visual Basic 8 (2005).NET 1.0.NET 1.1.NET 3.0.NET4.NET 2.0.NET 3.5初学者.NETVisual Basic
移动边框不可见的窗体
一个使您可以通过单击窗体表面来拖动窗体的类。
引言
我最近编写了一个应用程序,需要使用自定义界面,而皮肤化应用程序的第一步是移除窗体的边框,通过设置
FormBorderStyle = Windows.Forms.FormBorderStyle.None
移除边框后,主窗体可以获得任意形状。但这给我们留下了一个问题,即**用户如何移动窗体?** 因此,我们需要编写一些自定义代码来实现这一点,这就是我编写了一个名为 MoveFormWithoutBorder
的类的原因。
关于代码的一些说明
全局变量,用于保存移动窗体所需的信息
'Control which will be used to drag the Form
Dim WithEvents HookedControl As Windows.Forms.Control
'Base Form
Dim BaseControlToMove As Control
事件
我们主要处理 HookedControl
的三个事件
MouseDown
MouseMove
MouseUp
1. MouseDown
在此处,我们将窗体的初始位置保存在一个全局变量 OffsetLocation
中,然后将 MoveHook
布尔变量设置为 True
Private Sub Control_MouseDown(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.MouseEventArgs) _
Handles HookedControl.MouseDown
If Disable = True Then Exit Sub
If e.Button = Windows.Forms.MouseButtons.Left Then
MoveHook = True
OffsetLocation = New Point(e.Location.X, e.Location.Y)
End If
End Sub
2. MouseMove
在此事件期间,计算差值,然后将其添加到 BaseControlToMove
的 Location
中
Private Sub Control_MouseMove(ByVal sender As Object, _
ByVal e As System.Windows.Forms.MouseEventArgs) Handles HookedControl.MouseMove
If Disable = True Then Exit Sub
If MoveHook = True Then
Dim Newx, NewY As Integer
Newx = e.Location.X - OffsetLocation.X
NewY = e.Location.Y - OffsetLocation.Y
BaseControlToMove.Location = New Point(BaseControlToMove.Location.X + Newx, _
BaseControlToMove.Location.Y + NewY)
End If
End Sub
3. MouseUp
这是在用户释放鼠标左键时触发的第三个事件。 在此点,我们清除标志 MoveHook
和 OffsetLocation
,以便可以重新开始移动窗体的过程。
Private Sub Control_MouseUp(ByVal sender As Object, _
ByVal e As System.Windows.Forms.MouseEventArgs) Handles HookedControl.MouseUp
If Disable = True Then Exit Sub
If e.Button = Windows.Forms.MouseButtons.Left Then
MoveHook = False
OffsetLocation = Nothing
End If
End Sub
方法
该类公开了两个方法来禁用或启用 Hook,以便可以根据需要禁用移动。
Public Sub DisableHook()
Disable = True
MoveHook = False
OffsetLocation.X = 0
OffsetLocation.Y = 0
End Sub
Public Sub EnableHook()
Disable = False
End Sub
用法
'Create a Instance of this class and pass 2 Controls to Constructor
Dim FormMover As MoveFormWithoutBorder = New MoveFormWithoutBorder(Me, Me)
关注点
当移除边框时,这个类绝对派上用场,并且也避免了在各个地方重复编写相同的代码。
历史
- 2010年2月22日:初始发布