移动另一个控制的可视区域内的控制(Moving a control within another c

2019-10-17 03:34发布

我有一个PictureBox是一个内部TabPage ,当然这TabPage是一部分TabView ,这TabView是内Form 。 我希望用户能够在标签页中移动这个图片框。 为此,我现在用的是MouseDownMouseMoveMouseUp图片框的事件:

private void pictureBoxPackageView_MouseDown(object sender, MouseEventArgs e)
{
    if (!_mapPackageIsMoving)
    {
        _mapPackageIsMoving = true;
    }
} 

private void pictureBoxPackageView_MouseMove(object sender, MouseEventArgs e)
{
    if(_mapPackageIsMoving)
    {
        pictureBoxPackageView.Location = MousePosition; //This is not exact at all!
        return;
    }

    //Some other code for some other stuff when picturebox is not moving...
}

private void pictureBoxPackageView_MouseUp(object sender, MouseEventArgs e)
{
    if (_mapPackageIsMoving)
    {
        _mapPackageIsMoving = false; //Mouse button is up, end moving!
        return;
    }
}

但我的问题出在MouseMove事件。 只要我一按钮后,移动鼠标了,图片框跳出标签页的可见区域。

我需要知道如何以仅在标签页的矩形处理的举动,如果图片框被拖出标签视图的可见区域的,它不应该再除非用户将标签视图的可见矩形内移动鼠标。

任何帮助/提示将appriciated!

Answer 1:

你需要一个变量来保存图片框的原始位置:

从修改HansPassant答案 :

private Point start = Point.Empty;

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;
}


文章来源: Moving a control within another control's visible area