获取 MouseDown 和 DragDrop 的控件名称

Get name of controls for MouseDown and DragDrop

我有一个带有 Button 控件网格的 VB.net Windows 表单。如何最好地捕获拖放操作的按钮名称?如果我知道源按钮和目标按钮的名称,我就可以采取适当的措施。

您可以从 DragDrop 处理程序的参数中获取目标按钮和源按钮

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' If buttons are on Panel1 then 
    '     Me.Panel1.Controls().OfType(Of Button)()
    ' If buttons share some unique substring in name (to exclude other buttons)
    '     Me.Controls().OfType(Of Button)().Where(Function(b) b.Name.Contains("substring"))
    Dim myButtons = Me.Controls().OfType(Of Button)()
    ' add all the event handlers to the buttons in the list
    For Each b In myButtons
        b.AllowDrop = True
        AddHandler b.DragDrop, AddressOf Button_DragDrop
        AddHandler b.DragEnter, AddressOf Button_DragEnter
        AddHandler b.MouseMove, AddressOf Button_MouseMove
    Next
End Sub

' standard event handler for drag enter
Private Sub Button_DragEnter(sender As Object, e As DragEventArgs)
    If TypeOf e.Data.GetData(e.Data.GetFormats()(0)) Is Button Then e.Effect = DragDropEffects.Move
End Sub

' standard event handler for mouse move related to drag drop
Private Sub Button_MouseMove(sender As Object, e As MouseEventArgs)
    If e.Button = MouseButtons.Left Then DoDragDrop(sender, DragDropEffects.Move)
End Sub

' the key is getting the source and destination from the arguments
Private Sub Button_DragDrop(sender As Object, e As DragEventArgs)
    Dim destinationButton = DirectCast(sender, Button)
    Dim sourceButton = DirectCast(e.Data.GetData(e.Data.GetFormats()(0)), Button)
    MessageBox.Show($"Source: {sourceButton.Name}, Destination: {destinationButton.Name}")
End Sub