首页 > 解决方案 > 在鼠标移动中设置边界

问题描述

如何防止鼠标在图片框(500 x 500 像素)内拖动图像时从图片框(500 x 500 像素)中脱出?

在此处输入图像描述

这是鼠标事件:

private void pictureBox_Canvass_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            drag = true;
            //start = new Point(e.Location.X + (int)imageRect.Location.X, e.Location.Y + (int)imageRect.Location.Y);
            start = new Point((int)Shape.center.X - ((int)imageRect.Location.X - e.X), (int)Shape.center.Y - ((int)imageRect.Location.Y - e.Y));
        }
    }
    private void pictureBox_Canvass_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left && drag == true)
        {
            Point loc = new Point((int)((e.X - start.X) - (imageRect.Width / 2)), (int)((e.Y - start.Y) - (imageRect.Height / 2)));
            start.Offset(loc.X, loc.Y);
            imageRect.Location = start;
            Debug.WriteLine(start);
            pictureBox_Canvass.Invalidate();
        }
    }
    private void pictureBox_Canvass_MouseUp(object sender, MouseEventArgs e)
    {
        drag = false;
    }

标签: c#mouseevent

解决方案


推荐阅读