-2

我正在 Visual Studio 2012 中使用 C#.Net 创建一个应用程序。我想使用鼠标移动图片框。就像我们在桌面上移动图标一样。谁能帮我写代码?

4

2 回答 2

1

精简版...

    private Point StartPoint;

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            StartPoint = new Point(e.X, e.Y);
        }
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            PictureBox pb = (PictureBox)sender;
            Point pt = pb.Location;
            pt.Offset(e.X - StartPoint.X, e.Y - StartPoint.Y);
            pb.Location = pt;
        }
    }

正如 user1646737 指出的那样,您必须将 MouseDown() 和 MouseMove() 事件连接到这些处理程序。选择图片框。在属性窗格(默认右下角)中,单击“闪电”图标以获取事件列表。找到这些事件并将右侧的下拉列表更改为相应的方法。对所有图片框重复此操作。上面的代码将适用于多个控件,因为它使用sender将作为事件源控件的参数。

于 2013-11-11T07:14:13.627 回答
0

干得好:

    private bool _isMovingControl = false;
    private int _prevMouseX;
    private int _prevMouseY;

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        _prevMouseX = PointToClient(Cursor.Position).X;
        _prevMouseY = PointToClient(Cursor.Position).Y;
        _isMovingControl = true;
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        _isMovingControl = false;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        Point mouseLocation = PointToClient(Cursor.Position);

        if (_isMovingControl && (mouseLocation.X != _prevMouseX || mouseLocation.Y != _prevMouseY) )
        {
            if (mouseLocation.X > _prevMouseX)
            {
                //  Moved cursor to the right;

                pictureBox1.Left = pictureBox1.Left + (mouseLocation.X - _prevMouseX);
                _prevMouseX = mouseLocation.X;
            }
            else if (mouseLocation.X < _prevMouseX)
            {
                //  Moved cursor to the left;

                pictureBox1.Left = pictureBox1.Left - (_prevMouseX - mouseLocation.X);
                _prevMouseX = mouseLocation.X;
            }

            if (mouseLocation.Y > _prevMouseY)
            {
                //  Moved cursor toward the bottom;

                pictureBox1.Top = pictureBox1.Top + (mouseLocation.Y - _prevMouseY);
                _prevMouseY = mouseLocation.Y;
            }
            else if (mouseLocation.Y < _prevMouseY)
            {
                //  Moved cursor toward the top

                pictureBox1.Top = pictureBox1.Top - (_prevMouseY - mouseLocation.Y);
                _prevMouseY = mouseLocation.Y;
            }
        }
    }
于 2013-11-11T06:33:40.223 回答