在另一个控件的可见区域内移动控件

时间:2012-08-16 19:56:05

标签: c# winforms user-controls controls mouseevent

我有一个PictureBox位于TabPage内,当然这个TabPageTabView的一部分而TabView位于Form内{1}}。我希望用户能够在标签页中移动此图片框。为此,我使用了图片框中的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事件。只要按下按钮后移动鼠标,图片框就会跳出标签页的可见区域。

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

任何帮助/提示都会受到欢迎!

1 个答案:

答案 0 :(得分:3)

您需要一个变量来保存PictureBox的原始位置:

HansPassant answer修改:

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