Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I enable dragging and dropping an image from one PictureBox to another?

The following code snippet demonstrates how you can drag and copy an image from one picturebox (Source) another (Target):

[C#]

private void Form1_Load( object sender, EventArgs e )
{
  // Set AllowDrop of the Target PictureBox to true
  //   as this property cannot be set in the Designer
  pictureBox2.AllowDrop = true;
}

// Source PictureBox
private void pictureBox1_MouseMove( object sender, MouseEventArgs e )
{
  if ( e.Button == MouseButtons.Left )
    pictureBox1.DoDragDrop( pictureBox1.Image, DragDropEffects.All );
}

// Target PictureBox
// Drag Drop Effects
private void pictureBox2_DragEnter( object sender, DragEventArgs e )
{
  e.Effect =  e.Data.GetDataPresent( DataFormats.Bitmap )
    ? DragDropEffects.Copy: DragDropEffects.None;
}

// Set the image to be the dragged image
private void pictureBox2_DragDrop( object sender, DragEventArgs e )
{
  if ( e.Data.GetDataPresent( DataFormats.Bitmap ) )
    pictureBox1.Image = (Bitmap) e.Data.GetData( DataFormats.Bitmap ) ;
}

[Visual Basic]

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _
    Handles MyBase.Load
  ' Set AllowDrop of the Target PictureBox to true
  '   as this property cannot be set in the Designer
  pictureBox2.AllowDrop = True
End Sub

' Source PictureBox
Private Sub pictureBox1_MouseMove(ByVal sender As Object, _
    ByVal e As MouseEventArgs)
  If e.Button = MouseButtons.Left Then
    pictureBox1.DoDragDrop(pictureBox1.Image, DragDropEffects.All)
  End If
End Sub

' Target PictureBox
' Drag Drop Effects
Private Sub pictureBox2_DragEnter(ByVal sender As Object, _
    ByVal e As DragEventArgs)
  If e.Data.GetDataPresent(DataFormats.Bitmap) Then
    e.Effect = DragDropEffects.Copy
  Else
    e.Effect = DragDropEffects.None
  End If
End Sub

' Set the image to be the dragged image.
Private Sub pictureBox2_DragDrop(ByVal sender As Object, _
    ByVal e As DragEventArgs)
  If (e.Data.GetDataPresent(DataFormats.Bitmap)) Then
    pictureBox1.Image = CType((e.Data.GetData(DataFormats.Bitmap)), Bitmap)
  End If
End Sub

Contributed from George Shepherd's Windows Forms FAQ



Page view counter