2008年12月3日 星期三

設計可拖拉圖片(DragDrop Image)的Winform表單程式

如果想要在Winform中設計讓使用者可以拖拉圖片的功能,那麼就可以叫用PictureBox控制項的DoDragDrop方法來初始化拖曳作業,DoDragDrop方法需要兩個參數:一為代表正準備複製至DataObject的資料物件,另一個是指定此資料所允許之拖曳效果的DragDropEffects執行個體。

亞當斯來說明以一下此功能的設計步驟:

  1. 先準備一個Form表單,將準備移動的圖片(圖片中主角就是亞當斯最引以為傲,會寫Cat#的MiMi)先加到專案中,這邊亞當斯把圖片加入到專案的資源檔中,並且設定為內崁。ImageDragDrop01
  2. 在From畫面上配置兩個PictureBox控制項,先把左邊的PictureBox控制項Image圖片來源,設定為加入資源檔的圖片,右邊的PictureBox則不做任何設定。ImageDragDrop02
  3. 接下來這個步驟很重要因為PictureBox控制項的AllowDrop屬性沒辦法直接在設計的屬性視窗中設定,所以必須先在Form1表單的Load事件中,將目標PictureBox的AllowDrop屬性設定為True,接著在準備要拖曳的PictureBox之MouseDown事件中起始拖曳作業,程式碼如下:
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
      '設定PictureBoxRight可以允許拖拉
      PictureBoxRight.AllowDrop = True
    End Sub
    Private Sub PictureBoxLeft_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBoxLeft.MouseDown
      If PictureBoxLeft.Image IsNot Nothing Then
        PictureBoxLeft.DoDragDrop(PictureBoxLeft.Image, DragDropEffects.Move)
      End If
    End Sub



  4. 設定拖放作業中的目標PictureBox置放效果,先用DragEventArgs物件Data屬性的GetDataPresent方法判斷為圖片,再設定DragDropEffects列舉常數(亞當斯的這個範例是使用:Move)。
    Private Sub PictureBoxRight_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles PictureBoxRight.DragEnter
      If e.Data.GetDataPresent(DataFormats.Bitmap) Then

        e.Effect = DragDropEffects.Move

      End If

    End Sub



  5. 在目標的PictureBox之DragDrop事件中,設定PictureBox的Image屬性為拖曳過來的圖片。
    Private Sub PictureBoxRight_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles PictureBoxRight.DragDrop 

      If e.Data.GetDataPresent(DataFormats.Bitmap) Then
        PictureBoxRight.Image = CType(e.Data.GetData(DataFormats.Bitmap), Image)

        PictureBoxLeft.Image = Nothing

      End If

    End Sub



  6. 設計好表單後,執行程式,並且將左邊的PictureBox圖片直接拖曳到右邊的PictureBox,喔耶~成功了!!不過亞當斯只有撰寫從左邊拉到右邊的功能唷,如果你想要再從右邊拉到左邊,那麼就如法泡製整個設計步驟即可^_^。ImageDragDrop03