拖动图片框

Drag PictureBox

我想拖一个PictureBox,我已经成功了。但是我的应用程序没有 Windows photo viewer 那样顺利。我的意思是差异不是很大或任何东西,但它很明显。有什么我可以做的,让它不那么波涛汹涌吗?这是我的简单代码:

int MOUSE_X = 0;
int MOUSE_Y = 0;

public Form1()
{
    InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
    picBox.Image = Image.FromFile(@"D:\test_big.png");
    picBox.Width = 3300;
    picBox.Height = 5100;
}

private void picBox_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        MOUSE_X = e.X;
        MOUSE_Y = e.Y;
    }
}

private void picBox_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        picBox.Left = picBox.Left + (e.X - MOUSE_X);
        picBox.Top = picBox.Top + (e.Y - MOUSE_Y);
    }
}

这里有一个演示,演示了您的方法和评论中建议的方法。

测试您的代码生成:

而建议的代码:

using System.Runtime.InteropServices;
//...

private const int WM_SYSCOMMAND = 0x112;
private const int MOUSE_MOVE = 0xF012;

[DllImport("user32.dll")]
private static extern IntPtr SendMessage(
    IntPtr hWnd,
    int wMsg,
    IntPtr wParam,
    IntPtr lParam);

[DllImport("user32.dll")]
private static extern int ReleaseCapture(IntPtr hWnd);

private void picBox_MouseMove(object sender, MouseEventArgs e)
{
    if (!DesignMode && e.Button == MouseButtons.Left)
    {
        ReleaseCapture(picBox.Handle);
        SendMessage(picBox.Handle, WM_SYSCOMMAND, (IntPtr)MOUSE_MOVE, IntPtr.Zero);
    }
}

产生:

请注意,如果我这么说的话,我还使用了背景图像来使情况变得更糟。但是,如果没有背景图片,很难检测到使用了哪个代码片段。