无边窗口拖动(class)

11 篇文章 0 订阅

在网上抄的,写得很好。

http://www.cnblogs.com/yoker/articles/1221932.html

让咱们也玩窗体拖动,支持用TextBox,Label,ListBox...

创建一个类文件:MyDragForm.cs

代码如下:

[C#_Code]

using System;
using System.Drawing;
using System.Windows.Forms;

namespace Elephant.FormUtils
{
    class MyDragForm
    {  
        private static bool isMouseDown = false;
        private static Point mouseOffset;
        private static Form _form;

        public MyDragForm()
        {

        }

        ///
        /// 设定你要启用的控件
        ///
        /// 使用的控件对象,支持lable,textbox等
        public static void bindControl(Control control_)
        {
            //使用的控件
            if (control_ == null)
            {
                return;
            }
            _form = control_.FindForm();

            //加载消息
            control_.MouseMove += new MouseEventHandler(control_MouseMove);
            control_.MouseDown += new MouseEventHandler(control_MouseDown);
            control_.MouseUp += new MouseEventHandler(control_MouseUp);
        }

        private static void control_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Control control_ = sender as Control;
                //计算新点位置
                int offsetX = -e.X;
                int offsetY = -e.Y;
                if (!(control_ is System.Windows.Forms.Form))
                {
                    offsetX = offsetX - control_.Left;
                    offsetY = offsetY - control_.Top;
                }
                if (_form.FormBorderStyle != FormBorderStyle.None)
                {
                    offsetX = offsetX - SystemInformation.FrameBorderSize.Width;
                    offsetY = offsetY - SystemInformation.FrameBorderSize.Height - SystemInformation.CaptionHeight;
                }
                //重绘得新的位置
                mouseOffset = new Point(offsetX, offsetY);

                //鼠标点下,启示将要移动
                isMouseDown = true;
            }
        }

        private static void control_MouseMove(object sender, MouseEventArgs e)
        {
            //移动标志
            if (isMouseDown)
            {
                //赋予新的位置
                Point mouse = Control.MousePosition;
                mouse.Offset(mouseOffset.X, mouseOffset.Y);
                _form.Location = mouse;
            }
        }

        private static void control_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                //标志,不再移动
                isMouseDown = false;
            }
        }
    }
}

[/C#_Code]

调用代码:

image

MyDragForm.bindControl(this.lbl_systemname);

在页面拖动lbl_systemname这个标签,页面便一起拖动。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值