สำนักวิทยบริการและเทคโนโลยีสารสนเทศ (สวส.)

Office of Academic Resources and Information Technology

การสร้าง Tools Panel ใหเคลื่อนที่ตามเมาส์

Public Class Form1
    Dim pnPanel As New Panel                  '----- สร้าง Tools Panel ------
    Dim m_MouseIsDown As Boolean = False
    Dim fnX As Single = 0
    Dim fnY As Single = 0
    Dim pnX As Single = 0
    Dim pnY As Single = 0
   
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        pnPanel.Location = New Point(50, (50))                            '----- ตำแหน่ง Panel ----
        pnPanel.Size = CType(New Point(100, 48), Drawing.Size)
        pnPanel.BorderStyle = BorderStyle.FixedSingle
        pnPanel.BackColor = Color.LightGreen
        pnPanel.Parent = Me
        pnPanel.BringToFront()
        pnPanel.Show()
        AddHandler pnPanel.MouseMove, AddressOf Me.pnPanel_MouseMove      '----- เรียกใช้ Event MouseMove ----
        AddHandler pnPanel.MouseDown, AddressOf Me.pnPanel_MouseDown      '----- เรียกใช้ Event MouseDown ----
        AddHandler pnPanel.MouseUp, AddressOf Me.pnPanel_MouseUp          '----- เรียกใช้ Event MouseUp ----
        AddHandler Me.MouseMove, AddressOf Me.Form1_MouseMove             '----- เรียกใช้ Event Form1_MouseMove ----
    End Sub
   
Private Sub Form1_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        Me.Cursor = Cursors.Arrow
    End Sub
  
  Private Sub pnPanel_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)
              m_MouseIsDown = False
    End Sub
   
Private Sub pnPanel_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        fnX = CSng(Windows.Forms.Cursor.Position.X)
        fnY = CSng(Windows.Forms.Cursor.Position.Y)
        pnX = CSng(pnPanel.Location.X)
        pnY = CSng(pnPanel.Location.Y)
        m_MouseIsDown = True
    End Sub
   
    Private Sub pnPanel_MouseMove(ByVal sender As System.Object, ByVal e As     System.Windows.Forms.MouseEventArgs)
        Me.Cursor = Cursors.Hand
        '------------------
        If m_MouseIsDown = True Then
            pnPanel.Location = New Point(CInt((Windows.Forms.Cursor.Position.X - (fnX - pnX))), CInt((Windows.Forms.Cursor.Position.Y - (fnY - pnY))))
            pnPanel.BringToFront()
        End If
    End Sub
   
End Class