利用C#实现控件托拽调整外观

本文主要讨论一下制作类似vs.net的设计时控件可拖动的方法。具体思路是:制作一个容器控件,从Panel继承,名称为MyPanel;制作一个要拖动的控件,这里举例从Label继承,名称为MyLabel。当运行应用程序时,窗体加载MyPanel,MyPanel加载MyLabel,MyLabel在容器MyPanel中可以任意拖动。

  1. 从Label继承一个类,命名为MyLabel,在初始化函数中加入一些初始信息代码,比如:
    public MyLabel()
    {
           this.Text = "this is my custom label";
           this.Width = 200;
           this.BackColor = System.Drawing.Color.White;
    }
  2. 声明一个Point对象,该对象(作为一个变量)决定在什么情况下移动窗体。
    Point mouseOffset;
  3. 声明获得绝对坐标的API。
    [DllImport("user32.dll")]
    static extern bool ClientToScreen(IntPtr hWnd,ref Point lp);
  4. 重写OnMouseDown方法,加入如下代码:
    //获得鼠标的相对坐标的相反数
    mouseOffset = new Point(-e.X,-e.Y);
  5. 重写OnMouseMove方法,加入如下代码:
    if (e.Button == MouseButtons.Left)
    {
        //获得父容器Location的绝对坐标值
        Point lPoint = this.Parent.Location;
        bool tmp = ClientToScreen(this.Parent.Handle,ref lPoint);
        
        //获得当前鼠标相对与父容器的坐标
        Point mousePoint = new Point(Control.MousePosition.X-lPoint.X,Control.MousePosition.Y-lPoint.Y);
        //移动控件
        mousePoint.Offset(mouseOffset.X,mouseOffset.Y);
        //设置位置
        this.Location = mousePoint;
    }
  6. 从Panel继承一个类,此类为容器,名称为MyPanel在初始化函数中加入一些初始信息代码,比如:
    public MyPanel()
    {
        this.Width = 400;
        this.Height = 300;
        this.BorderStyle = BorderStyle.Fixed3D;
        this.BackColor = Color.Gray;
        this.Location = new Point(0,0);
        this.SetStyle(ControlStyles.Selectable,true);
        this.SetStyle(ControlStyles.DoubleBuffer,true);
        this.SetStyle(ControlStyles.UserPaint,true);
        this.SetStyle(ControlStyles.AllPaintingInWmPaint,true);
        this.Dock = DockStyle.Fill;
        MyLabel label = new MyLabel();
        label.Location = new Point(100,100);
        this.Controls.Add(label);
        MyLabel label2 = new MyLabel();
        label2.Location = new Point(100,200);
        this.Controls.Add(label2);
    }
  7. 在windows窗体代码的初始化函数的最后加上如下代码,手动添加MyPanel对象:
    MyPanel panel = new MyPanel();
    panel.Location = new Point(0,0);
    this.Controls.Add(panel);

OK,运行一下即可实现对象托拽。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值