1

这个问题与我的另一个问题有关,可以在这里找到。我想PictureBox在它的父容器中移动 a TabPage(如果它确实有任何区别!)使用下面的代码可以完成移动:

private Point start = Point.Empty; 
private bool _mapPackageIsMoving;    

void pictureBoxPackageView_MouseUp(object sender, MouseEventArgs e) { 
  _mapPackageIsMoving = false; 
} 

void pictureBoxPackageView_MouseMove(object sender, MouseEventArgs e) { 
  if (_mapPackageIsMoving) { 
    pictureBoxPackageView.Location = new Point( 
                             pictureBoxPackageView.Left + (e.X - start.X),  
                             pictureBoxPackageView.Top + (e.Y - start.Y)); 
  } 
} 

void pictureBoxPackageView_MouseDown(object sender, MouseEventArgs e) { 
  start = e.Location; 
  _mapPackageIsMoving = true; 
} 

现在我的问题是,这种控制的移动是没有限制的。用户可以将控件从我的图片框所在的可见区域拖出几公里TabPage。我试图通过更改这样的MouseMove事件来添加一些移动限制,以至少防止它超出标签页的Left可见Right区域:

void pictureBoxPackageView_MouseMove(object sender, MouseEventArgs e) { 
  if (_mapPackageIsMoving) { 
   //Added condition
  if (pictureBoxPackageView.Left >= 0 && pictureBoxPackageView.Right >= 0)
    pictureBoxPackageView.Location = new Point( 
                             pictureBoxPackageView.Left + (e.X - start.X),  
                             pictureBoxPackageView.Top + (e.Y - start.Y)); 
  } 
} 

但是上面代码的问题是,每当图片框碰到容器的右侧或左侧并且LeftorRight等​​于 0 时,我就不能再移动控件了。

任何有助于限制Left, Right, Top and Bottom图片框容器内的移动的帮助/提示都将得到应用!

4

2 回答 2

3

您可以无条件移动该框(不测试当前位置)并对您的新位置有限制:

int nx = Math.Min(Math.Max(pictureBoxPackageView.Left + (e.X -start.X),0),pictureBoxPackageView.Parent.Width-pictureBoxPackageView.Width);
int ny = Math.Min(Math.Max(pictureBoxPackageView.Top + (e.Y -start.Y),0),pictureBoxPackageView.Parent.Height-pictureBoxPackageView.Height);

pictureBoxPackageView.Location = new Point(nx,ny);
于 2012-08-17T07:54:09.580 回答
-2

我认为如果您添加以下代码,它会移动项目而不作为选项卡到顶部。

//- MouseDownLocation.X
 //- MouseDownLocation.Y 

       int nx = Math.Min(Math.Max(label1.Left - MouseDownLocation.X + (e.X - start.X), 0), label1.Parent.Width - label1.Width);
       int ny = Math.Min(Math.Max(label1.Top - MouseDownLocation.Y + (e.Y - start.Y), 0), label1.Parent.Height - label1.Height);
于 2017-05-03T13:16:14.100 回答