2013-10-11 57 views
0

我需要拖動窗體上的任何標籤。使用鼠標拖動窗體中的任何標籤

我使用此代碼,問題是它只移動1標籤label1 我可以複製粘貼幾次,它的工作原理,但我使用代碼來向窗體中添加新的標籤,並且代碼沒有看到他們。

如何點擊並拖動窗體上的任何標籤?

Public Class Form1 
    Dim lbl As Label 
    Dim Off As Point 
    Private Sub obj1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles label1.MouseDown 

     Off.X = MousePosition.X - sender.Left 
     Off.Y = MousePosition.Y - sender.Top 
    End Sub 
    Private Sub obj1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles label1.MouseMove 
     If e.Button = MouseButtons.Left Then 
      sender.Left = MousePosition.X - Off.X 
      sender.Top = MousePosition.Y - Off.Y 
     End If 
    End Sub 
End Class 
+0

varocarbas第一次回答您......您需要連接mouseXXX處理程序,以獲得您在代碼中創建的新標籤...顯示該代碼,因爲它更可能出現問題的位置 – Plutonix

+0

我現在已經做了,謝謝給他這麼多,但我仍然困惑,我不想要他的時間,我會很感激,如果有人只是複製代碼和正確的身份證,並粘貼在這裏,這將是偉大的,甚至行 – user2581791

+1

...我會喜歡它如果有人也爲我做我的工作。展示代碼,您在哪裏製作新標籤......這就是問題幾乎可以肯定的地方。在varocarbas的代碼中沒有什麼可以糾正的,我們需要看看你是如何使用它的。 – Plutonix

回答

1

「我想拖位於表單中任何標籤」

而不是硬接線的「手柄xxx.yyy」條款的處理程序,將它們連接起來,在運行時的負載( )事件表格:

Public Class Form1 

    Dim Off As Point 

    Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load 
     WireLabels(Me) 
    End Sub 

    Private Sub WireLabels(ByVal cont As Control) 
     For Each ctl As Control In cont.Controls 
      If TypeOf ctl Is Label Then 
       AddHandler ctl.MouseDown, AddressOf obj1_MouseDown 
       AddHandler ctl.MouseMove, AddressOf obj1_MouseMove 
      ElseIf ctl.HasChildren Then 
       WireLabels(ctl) 
      End If 
     Next 
    End Sub 

    Private Sub obj1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) 
     Off.X = MousePosition.X - sender.Left 
     Off.Y = MousePosition.Y - sender.Top 
    End Sub 

    Private Sub obj1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) 
     If e.Button = MouseButtons.Left Then 
      sender.Left = MousePosition.X - Off.X 
      sender.Top = MousePosition.Y - Off.Y 
     End If 
    End Sub 

End Class 

很明顯,你也可以在運行時使用AddHandler來創建任何標籤。

0

你的代碼改成這樣:

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

    Off.X = MousePosition.X - sender.Left 
    Off.Y = MousePosition.Y - sender.Top 
End Sub 
Private Sub obj1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) 
    If e.Button = MouseButtons.Left Then 
     sender.Left = MousePosition.X - Off.X 
     sender.Top = MousePosition.Y - Off.Y 
    End If 
End Sub 

而在你的窗體加載有這樣的:

AddHandler label1.MouseDown, Addressof obj1_MouseDown 
AddHandler label1.MouseMove, Addressof obj1_MouseMove 

而在你的標籤創建代碼:

dim aLabel as label = new Label 
AddHandler aLabel.MouseDown, Addressof obj1_MouseDown 
AddHandler aLabel.MouseMove, Addressof obj1_MouseMove 
... 

你需要將處理程序添加到對象之後創建,否則表單不知道如何處理事件。

+0

感謝大家對我的幫助,我感謝它的完美工作Idle_Mind謝謝 – user2581791