Achilles Stand
Achilles Stand

Reputation: 67

Moving control in runtime

I'm with a problem moving a label on a panel. When I move this label, reached the top and left (0.0), the label respects the top and left. To spend half of the screen, the label exceeds the panel as shown in picture.

enter image description here

My codes:

public partial class frmStandard : Form
{
    Point startposition;    
}

public void MouseDown(object sender, MouseEventArgs e)
{
    startposition = e.Location;
}

public void MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left) 
    {   
        ((Label)sender).Left = Math.Max(0, e.X + ((Label)sender).Left - startposition.X);
        ((Label)sender).Top = Math.Max(0, e.Y + ((Label)sender).Top - startposition.Y);
    }
}

I need the label does not exceed the panel size.What should be added in the codes?

Upvotes: 2

Views: 1142

Answers (1)

TaW
TaW

Reputation: 54433

You need to check the other Borders.

You will have to use the dimension data of the containing Panel for this.

In the spirit of keeping things dynamic, as your code already is, I use he Label's Parent instead of referring to just the one Panel:

private void MouseMove(object sender, MouseEventArgs e)
{
  Label L = (Label)sender;
  Rectangle PR = L.Parent.ClientRectangle;

  if (e.Button == MouseButtons.Left)
  {
     L.Left = Math.Min(Math.Max(0, e.X + L.Left - startposition.X), PR.Right - L.Width);
     L.Top = Math.Min( Math.Max(0, e.Y + L.Top - startposition.Y), PR.Bottom - L.Height);
  }
}

To keep it even more general, one could replace Label with Control and let the user move other Controls around wit the same pieces of code..

Upvotes: 5

Related Questions