winform上创建可拖动缩放的控件

来源:互联网 发布:卖钣金展开软件 编辑:程序博客网 时间:2024/06/05 10:25
1. 定义变量

private Control downCtrl;//鼠标按下控件

private Point  downLoc;//鼠标按下位置

bool ctrlMove;//标记拖动状态

bool ctrlZoom;//标记缩放状态

2. 定义控件的MouseDown事件

private void Control_MouseDown(object sender, MouseEventArgs e)

{

    downCtrl = sender as Control;

    downLoc = e.Location;

    if(downCtrl.Cursor == Cursors.SizeAll)

    {

         ctrlMove = true;

         ctrlZoom = false;

    }

    else if(downCtrl.Cursor == Cursors.SizeNWSE | downCtrl.Cursor == Cursors.SizeNS | downCtrl.Cursor == Cursors.SizeWE)

    {      

 

         ctrlMove = false;

         ctrlZoom = true;

     }

}

3. 定义控件的MouseMove事件

private void Control_MouseMove(object sender, MouseEventArgs e)

{

    Control control = sender as Control;

    //获取控件相对于容器的位置

    Point p1= Control.MousePosition;

    Point p2 = panel1.PointToClient;

    if (x >= control.Right - 5 &&  x<= control.Right + 5 && y >= control.Bottom - 5 && y <= control.Bottom + 5) //右下角

    {

         control.Cursor = Cursors.SizeNWSE;

    } 

    else if (x >= control.Left - 5 &&  x<= control.Right + 5 && y >= control.Bottom - 5 &&  y<= control.Bottom + 5) //下边界

    {

         control.Cursor = Cursors.SizeNS;

   }

    else if(x >= control.Right - 5 &&  x<= control.Right + 5 && y >= control.Top - 5 &&  y<= control.Bottom + 5) //右边界

    {

         control.Cursor = Cursors.SizeWE;

    }

    else

    {

        control.Cursor = Cursors.SizeAll;

    }

     if ((e.BUtton == MouseButtons.Left) && ctrlMove)

     {

         int pos_x, pos_y;

         pos_x = downCtrl.Location.X + (e.X-downLoc.X);

         pos_y = downCtrl.Location.Y + (e.Y-downLoc.Y)

        downCtrl.Location = new Point(pos_x, pos_y);

     }

     if ((e.BUtton == MouseButtons.Left) && ctrlZoom)

     {

         control.Width += e.X - downLoc.X;

         control.Height +=e.Y - downLoc.Y;

         downCtrl = e.Location;

     }

}