講述VB.NET實現(xiàn)拖動圖片
學習VB.NET時,你可能會遇到VB.NET實現(xiàn)拖動圖片問題,這里將介紹VB.NET實現(xiàn)拖動圖片問題的解決方法,在這里拿出來和大家分享一下。盡管VB.NET實現(xiàn)拖動圖片并不像拖放文本那樣經常用到,然而它在許多應用程序中仍然是很有用的。實際上這兩者之間也沒有什么不同,只不過是數(shù)據(jù)類型發(fā)生了變化而已。
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將引發(fā)一個意外。還應該注意到的是在DragEnter和DragDrop事件中代碼檢測CTRL鍵是否被按下,從而決定是否是復制還是VB.NET實現(xiàn)拖動圖片。
為什么值會不同呢?在 DragEnter事件中,當鼠標左鍵按下時,產生的值是1,在加上CTRL的值8,從而值為9。見KeyState枚舉列表DragEventArgs.KeyState Property到目前為止,這兩個例子處理的都是同一窗體不同控件間的拖放,然而在同一應用程序的不同窗體上同樣適用。
【編輯推薦】