如何在C#.Net中使用鼠标指针在窗口内移动图片框

时间:2013-11-11 06:04:02

标签: c#

我在Visual Studio 2012中使用C#.Net创建应用程序。我想使用鼠标移动图片框。与我们在桌面上移动图标相同。 任何人都可以帮我解释代码吗?

2 个答案:

答案 0 :(得分: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()事件连接到这些处理程序。选择PictureBox。在“属性窗格”(默认情况下右下角)中,单击“闪电箭”图标以获取事件列表。找到这些事件并将相应方法的右下角更改为。对所有PictureBox重复此操作。上面的代码适用于多个控件,因为它使用sender参数作为事件的源控件。

答案 1 :(得分: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;
            }
        }
    }