2017-09-05 87 views
0

請原諒我,如果這是一個愚蠢的問題,但我沒有經驗,並且沒有找到對此問題的答案。WinForms拖放:標籤在跟隨鼠標前「跳開」

For i = 0 To _tree.treedata.Rows.Count - 1 

     Dim tb As New Label 

     tb.Name = CStr(i) 

     tb.AutoSize = True 
     tb.MaximumSize = New Size(tb.Width, 70) 
     tb.MinimumSize = New Size(tb.Width, 0) 

     tb.Location = New Point(treedata.Rows(i)(11),treedata.Rows(i)(4)) 

     AddHandler tb.MouseMove, AddressOf obj1_MouseMove 
     AddHandler tb.MouseDown, AddressOf obj1_MouseDown 

     Form8.Panel1.Controls.Add(tb) 

    Next 

使用MouseMove事件我想拖動標籤上:

我在面板上的代碼依賴於存儲在一個DataTable(treedata)數據扣帽子(Form8.Panel1)面板跟隨鼠標:

Private Sub obj1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) 

    If e.Button = MouseButtons.Left Then 
     sender.Location = New Point(Form8.MousePosition.X, Form8.MousePosition.Y) 

    End If 
End Sub 

什麼,現在的情況是,當我點擊的標籤上,並希望跟隨首次出現的「跳走」,意思是移動頗有幾分遠離鼠標的位置,只需輕點鼠標然後跟隨鼠標。有沒有人知道我必須改變以避免標籤的初始跳躍?

+0

'MousePosition'是不是你想要的,你需要將這些座標轉換成控制座標。 – DonBoitnott

+0

就像這樣:https://stackoverflow.com/questions/28531058/find-position-of-mouse-relative-to-control-rather-than-screen#28533224。關於'PointToClient'的部分可能是最相關的。 – DonBoitnott

+0

謝謝,明白了! – dunkleosteus

回答

0

原來相當簡單,只是MousePosition沒有給出相對於面板的位置。這工作:

 Dim newloc As Point = Form8.Panel1.PointToClient(Form8.MousePosition) 
     sender.Location = newloc 
+1

不幸的是,VB.NET編譯器允許這樣做,真的非常適合使用正確的標識符名稱。它是Control.MousePosition,使得它更加明顯,PointToClient是必需的,它返回的位置與窗體座標無關。 –