2009-10-01 如何於執行期拖曳移動控制項 10188 0 VB.Net / C#.Net / 摘要:如何於執行期拖曳移動控制項 VB.Net執行期拖拉移動控制項範例方法1:Public Class Form1 Dim pos As MouseEventArgs = Nothing '用來記錄滑鼠點下起始位置 Private Sub Form1_Load(ByVal s As Object, ByVal e As EventArgs) Handles MyBase.Load ' Loop 表單中控制項 For Each ctl As Control In Me.Controls 'AddHandler 陳述式 : 執行階段使事件與事件處理常式產生關聯。 AddHandler ctl.MouseMove, AddressOf Ctl_MouseMove AddHandler ctl.MouseDown, AddressOf Ctl_MouseDown Next End Sub Private Sub Ctl_MouseMove(ByVal s As Object, ByVal e As MouseEventArgs) Dim c As Control = DirectCast(s, Control) ' 型別轉換作業 If c.Capture Then ' 控制項是否 Capture Mouse ' 指定控制項新位置 c.Location = New Point(e.X + c.Location.X - pos.X, e.Y + c.Location.Y - pos.Y) End If End Sub Private Sub Ctl_MouseDown(ByVal s As Object, ByVal e As MouseEventArgs) pos = e ' 記錄控制項舊位置 End Sub End Class方法2:Public Class Form1 Private Const WM_NCLBUTTONDOWN = &HA1 Private Const HTCAPTION = 2 Private Sub Form1_Load(ByVal s As Object, ByVal e As EventArgs) Handles MyBase.Load ' Loop 表單中控制項 For Each ctl As Control In Me.Controls 'AddHandler 陳述式 : 執行階段使事件與事件處理常式產生關聯。 AddHandler ctl.MouseDown, AddressOf Ctl_Drag Next End Sub Private Sub Ctl_Drag(ByVal s As Object, ByVal e As MouseEventArgs) If e.Button = MouseButtons.Left Then Dim c As Control = DirectCast(s, Control) c.Capture = False DefWndProc(Message.Create _ (c.Handle, WM_NCLBUTTONDOWN, New IntPtr(HTCAPTION), IntPtr.Zero)) End If End Sub End Class PS: 可於Run-Time 使用者拖拉控件後的 MouseUp 事件記錄控制項所在位置 , 另外在 Form_Load 事件撰寫載入控件位置的程式碼, 即可達到讓使用者自行調整版面的效果 回首頁