d.
If (e.Data.GetDataPresent(DataFormats.Text)) Then
' Display the copy cursor.
e.Effect = DragDropEffects.Copy
Else
' Display the no-drop cursor.
e.Effect = DragDropEffects.None
End If
End Sub
Private Sub TextBox2_DragDrop(ByVal sender As Object, ByVal e As _
System.Windows.Forms.DragEventArgs) Handles TextBox2.DragDrop
' Paste the text.
TextBox2.Text = e.Data.GetData(DataFormats.
End Sub
在上面的例子中,MouseDown事件是用来判断鼠标是否按下的,MouseMove事件中用到了DoDragDrop方法。尽管你可以在MouseDown事件中来初始化Drag,然而这么做会带来出人意料之外的结果。在用户点击控件时,将显示no-drag
指针。DoDragDrop方法有两个参数
data,这个例子中代表的是第一个TextBox的Text属性。
allowedEffects,这个例子中是只允许复制。
在MouseMove事件中MouseIsDown标志设置成了False,尽管在这个例子没有必要,但是如果你有很多控件支持拖放时,你将会得到一个运行时例外。
在DragEnter事件中,GetDataPresent方法检查正在拖动的数据格式,在本例中是文本,所以Effect属性设置成复制,同时也显示copy指针。
在DragDrop事件中,GetData方法用来从DataObject中获得文本,并把它送给目标文本框。
拖动图片
尽管拖放图片并不像拖放文本那样经
常用到,然而它在许多应用程序中仍然是很有用的。实际上这两者之间也没有什么不同,只不过是数
据类型发生了变化而已。
1、 在Form中添加两个PictureBox控件。
2、 在代码窗体中添加如下代码
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
' Enable dropping.
PictureBox2.AllowDrop = True
End Sub
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
' Set a flag to show that the mouse is down.
m_MouseIsDown = True
End If
End Sub
Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As _
System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
If m_MouseIsDown Then
' Initiate dragging and allow either copy or move.
PictureBox1.DoDragDrop(PictureBox1.Image, DragDropEffects.Copy Or _
DragDropEffects.Move)
End If
m_MouseIsDown = False
End Sub
Private Sub PictureBox2_DragEnter(ByVal sender As Object, ByVal e As _
System.Windows.Forms.DragEventArgs) Handles PictureBox2.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
Private Sub PictureBox2_DragDrop(ByVal sender As Object, ByVal e As _
System.Windows.Forms.DragEventArgs) Handles PictureBox2.DragDrop
' Assign the image to the PictureBox.
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
注意到上面的例子中第二个PictureBox控件的AllowDrop属性是在Form1_load事件中设置的,这是因为
设计时PictureBox并没有AllowDrop属性。
在MouseDown事件中,代码首先检测是否有要赋给PictureBox的图片;如果没有的话,当你移动图片后,接下来的click将引发一个意外。
还应该注意到的是在DragEnter和DragDrop事件中代码检测CTRL键是否被按下,从而决定是否是复制还是移动图片。为什么值会不同呢?在DragEnter事件中,当