【发布时间】:2022-04-12 08:01:21
【问题描述】:
我正在处理一个包含十个图片框的表单。孩子们应该能够将图片从一个图片框拖到其他任何一个图片框中。我阅读了一篇出色的 Microsoft 文章,其中解释了在两个图片框之间设置拖放的步骤。有五个子例程可以将一种方式拖放到第二个图片框中。
我担心的是,如果表单有十个图片框,并且用户可以在十个框中的任何一个之间拖放,那就是很多代码和很多子例程。
有没有更优雅的方法来做到这一点?我在下面放置了代码,用于在两个图片框之间进行拖放。我正在使用 Visual Basic 2010 Express。谢谢。
' Enable dropping.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
PictureBox2.AllowDrop = True
End Sub
' Set a flag to show that the mouse is down for PictureBox1
Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As _
System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
If Not PictureBox1.Image Is Nothing Then
MouseIsDown = True
End If
End Sub
' Initiate dragging and allow either copy or move for PictureBox1
Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As _
System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
If MouseIsDown Then
PictureBox1.DoDragDrop(PictureBox1.Image, DragDropEffects.Copy Or _
DragDropEffects.Move)
End If
MouseIsDown = False
End Sub
'Copy or Move data from PictureBox1
Private Sub PictureBox1_DragEnter(ByVal sender As Object, ByVal e As _
System.Windows.Forms.DragEventArgs) Handles PictureBox1.DragEnter
If e.Data.GetDataPresent(DataFormats.Bitmap) Then
' Check for the CTRL key.
If e.KeyState = 9 Then
e.Effect = DragDropEffects.Copy
Else
e.Effect = DragDropEffects.Move
End If
Else
e.Effect = DragDropEffects.None
End If
End Sub
' Assign the image to the PictureBox2
Private Sub PictureBox2_DragDrop(ByVal sender As Object, ByVal e As _
System.Windows.Forms.DragEventArgs) Handles PictureBox2.DragDrop
PictureBox2.Image = e.Data.GetData(DataFormats.Bitmap)
' If the CTRL key is not pressed, delete the source picture.
If Not e.KeyState = 8 Then
PictureBox1.Image = Nothing
End If
End Sub
【问题讨论】:
标签: vb.net visual-studio-2010 drag-and-drop