Moving a control within another control's visi

2019-08-11 04:57发布

问题:

I have a PictureBox that is inside a TabPage, and of course this TabPage is part of a TabView and this TabView is inside a Form. I want users be able to move this picture box within the tab page. For this I am using the MouseDown, MouseMove and MouseUp events of the picture box:

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

But my problem lies in the MouseMove event. As soon as I move mouse after button down, the picture box jumps out of tab page's visible area.

I need to know how to handle the move only within the rectangle of the tab page, and if picture box is being dragged out of tab view's visible area, it shouldn't move anymore unless user brings the mouse inside the tab view's visible rectangle.

Any helps/tips will be appriciated!

回答1:

You need a variable to hold the original position of the PictureBox:

Modified from a 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;
}