【Winform】无边框窗体拖动

无边框的窗体实现鼠标拖动

FormBordStyle属性设为None

FormBordStyle属性设为None

方法1

窗体里面加个Label控件作为“标题栏”
在这里插入图片描述

绑定Label的MouseMove和MouseDown事件
在这里插入图片描述

代码如下:

		private int mouseX;
        private int mouseY;
        private void label1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseX = e.X;
                mouseY = e.Y;
            }
        }
        private void label1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Location = new Point(this.Location.X + (e.X - mouseX), this.Location.Y + (e.Y - mouseY));
            }
        }

实现效果:鼠标左键按住Label拖动即可实现窗体拖动

方法2

直接绑定窗体的MouseDown事件
在这里插入图片描述
代码如下:

		[DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;
        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            //拖动窗体
            ReleaseCapture();
            SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
        }

参考:原文地址

实现效果:鼠标左键按住窗体任意位置拖动即可实现窗体拖动

方法2有大佬能解释下原理吗?在线求助

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值