vb.net 鼠标拖拽窗体
简单的一个类型,可以让鼠标在窗体内任意位置进行拖拽。
使用方法很简单:
使用方法很简单:
' 让当前窗体可以用鼠标拖拽
Dim dform As New DragForm(Me)
' 是否使用手型鼠标指针
dform.UseHandCursor = True
' 切换启用、关闭
dform.SwitchEnable()
' 关闭功能
dform.DragEnable = False
类型代码如下:''' <summary>拖拽窗体</summary>
Public Class DragForm
Private Declare Function LoadCursorA Lib "user32" (ByVal hInstance As IntPtr, ByVal lpCursorName As Integer) As IntPtr
Private targetForm As Form
Private mouseOffset As Point
Private isMouseDown As Boolean = False
Private _DragEnable As Boolean = False
Private _usehandCur As Boolean = True
Private handcur As Cursor
Sub New(ByVal targetForm As Form)
Me.targetForm = targetForm
regEvent()
Try
handcur = New Cursor(LoadCursorA(IntPtr.Zero, 32649))
Catch ex As Exception
handcur = Cursors.Hand
End Try
End Sub
Protected Overrides Sub Finalize()
unregEvent()
MyBase.Finalize()
End Sub
Friend Sub regEvent()
If Not _DragEnable Then
AddHandler targetForm.MouseDown, AddressOf target_MouseDown
AddHandler targetForm.MouseMove, AddressOf target_MouseMove
AddHandler targetForm.MouseUp, AddressOf target_MouseUp
_DragEnable = True
End If
End Sub
Friend Sub unregEvent()
If _DragEnable Then
RemoveHandler targetForm.MouseDown, AddressOf target_MouseDown
RemoveHandler targetForm.MouseMove, AddressOf target_MouseMove
RemoveHandler targetForm.MouseUp, AddressOf target_MouseUp
_DragEnable = False
isMouseDown = False
End If
End Sub
Private Sub target_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
If _usehandCur Then targetForm.Cursor = handcur
Dim xOffset As Integer
Dim yOffset As Integer
If e.Button = Windows.Forms.MouseButtons.Left Then
xOffset = -e.X - SystemInformation.FrameBorderSize.Width
yOffset = -e.Y - SystemInformation.CaptionHeight - _
SystemInformation.FrameBorderSize.Height
mouseOffset = New Point(xOffset, yOffset)
isMouseDown = True
End If
End Sub
Private Sub target_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
If isMouseDown Then
Dim mousePos As Point = Control.MousePosition
mousePos.Offset(mouseOffset.X, mouseOffset.Y)
targetForm.Location = mousePos
End If
End Sub
Private Sub target_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
If _usehandCur Then targetForm.Cursor = Cursors.Default
If e.Button = Windows.Forms.MouseButtons.Left Then
isMouseDown = False
End If
End Sub
''' <summary>是否启用(默认是)</summary>
Property DragEnable As Boolean
Get
Return _DragEnable
End Get
Set(ByVal value As Boolean)
If value Then
regEvent()
Else
unregEvent()
isMouseDown = False
End If
End Set
End Property
''' <summary>切换启用</summary>
Function SwitchEnable() As Boolean
DragEnable = Not DragEnable
Return _DragEnable
End Function
''' <summary>是否使用手型鼠标指针</summary>
Property UseHandCursor As Boolean
Get
Return _usehandCur
End Get
Set(ByVal value As Boolean)
_usehandCur = value
If Not _usehandCur Then targetForm.Cursor = Cursors.Default
End Set
End Property
End Class
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。