1. 程式人生 > >vb.net 實現無標題欄窗體拖拽功能

vb.net 實現無標題欄窗體拖拽功能

<pre name="code" class="vb">'較好用,沒有閃動  
  Declare Auto Function ReleaseCapture Lib "user32.dll" Alias "ReleaseCapture" () As Boolean
    'API ReleaseCapture函式是用來釋放滑鼠捕獲的
    Declare Auto Function SendMessage Lib "user32.dll" Alias "SendMessage" (ByVal hWnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As IntPtr
    '向windows傳送訊息
    Public Const WM_SYSCOMMAND As Integer = &H112&
    Public Const SC_MOVE As Integer = &HF010&
    Public Const HTCAPTION As Integer = &H2&
Private Sub frm1_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove
        If e.Button = MouseButtons.Left Then
            ReleaseCapture()
            SendMessage(Me.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0)
        End If


    End Sub

'這種方法會造成滑鼠點一下窗體瞬間移動到某處,有閃動現象
    Private mouseOffset As Point
    '記錄滑鼠指標的座標  
    Private isMouseDown As Boolean
    Private Sub frm1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown


        Dim xOffset As Integer
        Dim yOffset As Integer


        If (e.Button = 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 frm1_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove


        If (isMouseDown) Then
            Dim mousePos As Point = Control.MousePosition
            mousePos.Offset(mouseOffset.X, mouseOffset.Y)
            Location = mousePos
        End If


    End Sub


    Private Sub frm1_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseUp
        If (e.Button = MouseButtons.Left) Then
            isMouseDown = False
        End If
    End Sub