我想制作一个 Visual Basic 窗体,其中包含一组指定的元素,用户可以将这些元素拖动到窗体上的另一个位置。我怎样才能做到这一点?我在 Google 上查看过,并在 StackOverflow 上进行了一些搜索,但我一无所获。
感谢您的帮助!
最佳答案
我很久以前写过一篇关于这个主题的文章,可能对你有帮助。
Drag & Drop Files into Your Form or Control
在该示例中,我展示了如何将文件拖到窗体或控件中。您的要求略有不同,但拖动的基本思想保持不变。
看一下这个示例,它演示了如何将一个控件拖到窗体上的另一个控件中。
对于此示例,在表单上放置两个列表框 - ListBox1
和 ListBox2
,并添加以下代码:
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
运行应用程序并将控件拖到表单上的各个位置。
关于.net - 使 Visual Basic 窗体上的元素可拖动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16095045/