2

我想制作一个具有一组指定元素的 Visual Basic 表单,用户可以将这些元素拖到表单上的另一个位置。我怎样才能做到这一点?我查看了谷歌,并在 StackOverflow 上进行了一些搜索,但我一无所获。

谢谢你的帮助!

4

1 回答 1

4

我很久以前写过一篇关于这个主题的文章,这可能对你有帮助。

将文件拖放到您的表单或控件中

在该示例中,我展示了如何将文件拖到表单或控件中。您的要求略有不同,但有关拖动的基本思想保持不变。

看看这个示例,它演示了如何将一个控件拖到表单上的另一个控件中。对于此示例,在表单上放置两个列表框 -ListBox1ListBox2,并添加以下代码:

Private Sub Form2_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    ListBox1.AllowDrop = True
    ListBox2.AllowDrop = True

    ListBox1.Items.Add("Test Item 1")
    ListBox1.Items.Add("Test Item 2")
    ListBox1.Items.Add("Test Item 3")
    ListBox1.Items.Add("Test Item 4")

    ListBox2.Items.Add("Test Item 5")
    ListBox2.Items.Add("Test Item 6")
    ListBox2.Items.Add("Test Item 7")
    ListBox2.Items.Add("Test Item 8")

End Sub

Private Sub ListBoxes_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseDown, ListBox2.MouseDown
    Dim lb As ListBox = CType(sender, ListBox)
    lb.DoDragDrop(lb, DragDropEffects.Move)
End Sub

Private Sub ListBoxes_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles ListBox1.DragEnter, ListBox2.DragEnter
    e.Effect = DragDropEffects.Move
End Sub

Private Sub ListBoxes_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles ListBox1.DragDrop, ListBox2.DragDrop
    If TypeOf sender Is ListBox Then
        Dim lb As ListBox = CType(sender, ListBox)
        Dim srcLb As ListBox = e.Data.GetData(GetType(ListBox))
        If lb IsNot srcLb Then
            lb.Items.Add(srcLb.SelectedItem.ToString)
            srcLb.Items.Remove(srcLb.SelectedItem)
        End If
    End If
End Sub

现在将项目从一个列表框拖到另一个列表框中,反之亦然,看看效果。

编辑:

在窗体上移动控件

(在OP在评论中澄清后添加)

在表单上移动控件与我上面展示的拖动完全不同。您可以简单地捕获 MouseDown、MouseMove 和 MouseUp 事件来执行此操作。

这是一个例子。在表单上放很多控件,并添加以下代码:

Private Moving As Boolean
Private Sub Controls_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs)
    Dim ctl As Control = CType(sender, Control)
    Cursor.Position = PointToScreen(ctl.Location + New Point(ctl.Width \ 2, ctl.Height \ 2))
    Moving = True
End Sub

Private Sub Controls_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs)
    If Moving Then
        Dim ctl As Control = CType(sender, Control)
        ctl.Location = PointToClient(Cursor.Position - New Point(ctl.Width \ 2, ctl.Height \ 2))
    End If
End Sub

Private Sub Controls_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs)
    Moving = False
End Sub

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    For Each ctl As Control In Me.Controls
        ctl.Cursor = Cursors.SizeAll
        AddHandler ctl.MouseDown, AddressOf Controls_MouseDown
        AddHandler ctl.MouseUp, AddressOf Controls_MouseUp
        AddHandler ctl.MouseMove, AddressOf Controls_MouseMove
    Next
End Sub

运行应用程序并在窗体上到处拖动控件。

于 2013-04-19T00:47:39.700 回答