如何只允许在对象的边界内删除(图片框)

时间:2015-05-05 01:03:45

标签: c# winforms

这是我到目前为止的代码:

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    int maxX, minX, maxY, minY;

    minX = pictureBox2.Location.X;
    minY = pictureBox2.Location.Y;
    maxX = (pictureBox2.Size.Width) + minX;
    maxY = (pictureBox2.Size.Height) + minY;

    Point PictureLocation = new Point(e.X, e.Y);

    if (   (PictureLocation.X <= maxX)
        && (PictureLocation.X >= minX)
        && (PictureLocation.Y <= maxY)
        && (PictureLocation.Y >= minY)   )
    {
        MessageBox.Show("The drag is working");
        //Rest of the program is fine
    }
    else
    {
        MessageBox.Show("Please re-drag the item into the area");
    }
}

目前它所提出的是其他声明,我无法弄清楚原因。

附加: 如果有帮助的话,我也会在这种拖拽过程中使用一种微弱的形状,因为我发现上面的代码在我需要的地方的右下方有一个正确的区域,因此可以影响位置:

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    mdown = e.Location;
    form2.BackgroundImageLayout = ImageLayout.Zoom;
    form2.BackgroundImage = pictureBox1.Image;
    form2.Opacity = 0.5f;
    form2.MaximizeBox = false;
    form2.ControlBox = false;
    form2.Text = "";
    form2.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
    form2.Size = new Size(150, 150);
    form2.Show();
    Point pt = pictureBox1.PointToScreen(pictureBox1.Location);
    form2.Location = pt;
}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Left)
    {
        Point pt = pictureBox1.PointToScreen(new Point(-(form2.Width / 2) + e.X, -(form2.Height / 2) + e.Y));
        form2.Location = pt;
    }
}

2 个答案:

答案 0 :(得分:0)

e.Xe.Y给出的点是相对于引发事件的控件(图片框)。

所以你真的想要:

minX = 0;
minY = 0;
maxX = pictureBox2.Size.Width;
maxY = pictureBox2.Size.Height;

答案 1 :(得分:0)

因为第一个图片框是在它自己的位置0,0获取一个数据,所以通过使用它,以及我的图片框在同一个y位置的事实开始你得到这个:

minX = (pictureBox2.Location.X)-(pictureBox1.Location.X);
minY = 0;
maxX = ((pictureBox2.Location.X) - (pictureBox1.Location.X)) + (pictureBox2.Width);
maxY = 0 + (pictureBox2.Height);

感谢大家的帮助!