Preventing moving of a control out of its containe

2020-02-15 04:44发布

问题:

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

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

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.

Any helps/tips to achive limiting this movement inside the container for Left, Right, Top and Bottom of the picture box will be appriciated!

回答1:

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


回答2:

I think if you add the following code, it will move the item without snapping to the top as an option.

//- 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);