C# 实现拖拉控件改变位置与大小的方法

2019-12-30 19:13:45于丽

在上面的MouseMove中多了一个方法--ControlMove,这个就是根据不同的枚举值,计算控件的移动方式和大小的方法。该方法中同时对控件的最小宽度和高度做了处理。添加如下两个字段。


private int MinWidth = 20; //最小宽度
private int MinHeight = 20;//最小高度

 /// <summary>
 /// 控件移动
 /// </summary>
 private void ControlMove()
 {
  cPoint = Cursor.Position;
  int x = cPoint.X - pPoint.X;
  int y = cPoint.Y - pPoint.Y;
  switch (this.mpoc)
  {
   case MousePosOnCtrl.TOP:
    if (baseControl.Height - y > MinHeight)
    {
     baseControl.Top += y;
     baseControl.Height -= y;
    }
    else
    {
     baseControl.Top -= MinHeight - baseControl.Height;
     baseControl.Height = MinHeight;
    }
    break;
   case MousePosOnCtrl.BOTTOM:
    if (baseControl.Height + y > MinHeight)
    {
     baseControl.Height += y;
    }
    else
    {
     baseControl.Height = MinHeight;
    }
    break;
   case MousePosOnCtrl.LEFT:
    if (baseControl.Width - x > MinWidth)
    {
     baseControl.Left += x;
     baseControl.Width -= x;
    }
    else
    {
     baseControl.Left -= MinWidth - baseControl.Width;
     baseControl.Width = MinWidth;
    }
    break;
   case MousePosOnCtrl.RIGHT:
    if (baseControl.Width + x > MinWidth)
    {
     baseControl.Width += x;
    }
    else
    {
     baseControl.Width = MinWidth;
    }
    break;
   case MousePosOnCtrl.TOPLEFT:
    if (baseControl.Height - y > MinHeight)
    {
     baseControl.Top += y;
     baseControl.Height -= y;
    }
    else
    {
     baseControl.Top -= MinHeight - baseControl.Height;
     baseControl.Height = MinHeight;
    }
    if (baseControl.Width - x > MinWidth)
    {
     baseControl.Left += x;
     baseControl.Width -= x;
    }
    else
    {
     baseControl.Left -= MinWidth - baseControl.Width;
     baseControl.Width = MinWidth;
    }
    break;
   case MousePosOnCtrl.TOPRIGHT:
    if (baseControl.Height - y > MinHeight)
    {
     baseControl.Top += y;
     baseControl.Height -= y;
    }
    else
    {
     baseControl.Top -= MinHeight - baseControl.Height;
     baseControl.Height = MinHeight;
    }
    if (baseControl.Width + x > MinWidth)
    {
     baseControl.Width += x;
    }
    else
    {
     baseControl.Width = MinWidth;
    }
    break;
   case MousePosOnCtrl.BOTTOMLEFT:
    if (baseControl.Height + y > MinHeight)
   {
    baseControl.Height += y;
   }
   else
   {
    baseControl.Height = MinHeight;
   }
   if (baseControl.Width - x > MinWidth)
   {
    baseControl.Left += x;
    baseControl.Width -= x;
   }
   else
   {
    baseControl.Left -= MinWidth - baseControl.Width;
    baseControl.Width = MinWidth;
   }
   break;
  case MousePosOnCtrl.BOTTOMRIGHT:
   if (baseControl.Height + y > MinHeight)
   {
    baseControl.Height += y;
   }
   else
   {
    baseControl.Height = MinHeight;
   }
   if (baseControl.Width + x > MinWidth)
   {
    baseControl.Width += x;
   }
   else
   {
    baseControl.Width = MinWidth;
   }
   break;
 }
 pPoint = Cursor.Position;
}