防止控件从其容器中移出 [英] Preventing moving of a control out of its container
问题描述
这个问题与我的另一个问题有关,可以在这里找到可以在这里找到.我想在TabPage
的父容器中移动PictureBox
(如果确实有区别!)使用下面的代码可以完成移动:
This question is related to another question of mine which can be found here can be found here. I wanted to move a PictureBox
within its parent container which is a TabPage
(If it does make any difference!) Using the code below the movement can be done:
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
可见区域:
Now my problem is, There is no limit to this moving of control. User can drag the controls kilometers away from the visible area of the TabPage
which my picturebox is inside it. I tried to add some limits for movement by changing the MouseMove
event like this, to atleast prevent it from going out of the Left
and Right
visible area of the tabpage:
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));
}
}
但是上面代码的问题是,当图片框碰到容器的右侧或左侧并且Left
或Right
等于0时,我再也无法移动控件了.
But the problem with the code above is whenever the picturebox hits the right or left side of the container and the Left
or Right
get equal to 0, I can not move the control anymore.
任何帮助/提示以达到限制图片框Left, Right, Top and Bottom
的容器内部移动的目的!
Any helps/tips to achive limiting this movement inside the container for Left, Right, Top and Bottom
of the picture box will be appriciated!
推荐答案
您可以无条件移动框(不测试当前位置),并且对您的新位置有限制:
you can move the box unconditionally (no testing of the current location) and have a limitation for your new location:
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);
这篇关于防止控件从其容器中移出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!