如何使图片框在 Windows 表单中可拖放?

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

我在 C# 的 WinForms 中创建了一个 PictureBox,现在我想让它可以拖放,方法是单击并按住 PictureBox 并在表单中的某个点释放它。位置应设置为我放下 PictureBox 的位置。 我已经尝试过 DragDrop 事件、MouseUp、MouseDown、MouseMove,但都失败了,我需要一个合适的方法来解决这个问题。我不想将 PictureBox 移动到另一个 PictureBox

您可以在 MouseDown 和 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);
        }
}