Search code examples
c#winformsdrag-and-drop

How to make a Picture Box drag-and-droppable in Windows Forms?


I've created a PictureBox in C#'s WinForms, now I want to make it drag and droppable, by clicking and holding the PictureBox and releasing it at some point in the form. and the position should set to the point where I Dropped the PictureBox. I have tried DragDrop events, MouseUp, MouseDown, MouseMove, but failed, I need a proper way for this. I don't want to move a PictureBox into another PictureBox.


Solution

  • You can use the cursor position on MouseDown and MouseMove:

    private void picBox_MouseDown(object sender, MouseEventArgs e) 
    {
            mousePosition = e.Location;
    }
    private void picBox_MouseMove(object sender, MouseEventArgs e) 
    {
            if (e.Button == MouseButtons.Left) 
            {
                int dx = e.X - mousePosition.X;
                int dy = e.Y - mousePosition.Y;
                picBox.Location = new Point(picBox.Left + dx, picBox.Top + dy);
            }
    }