Windows Form Tips: 无边框窗口实现用鼠标拖拽的功能

12 篇文章 0 订阅

有时候,为了达到一些特定的UI效果,我们可能会将一个Windows Form设定为无边框的形式(FormBorderStyle设置为None),但这时,窗口也将失去正常的用鼠标拖拽的行为。但下面这个例子可以让无边框窗口的鼠标拖拽功能又恢复回来。注意这个例子只支持按住鼠标左键拖拽。


假设窗口为Form1,我们为Form1增加MouseDown的响应函数Form1_MouseDown,以及MouseMove的响应函数Form1_MouseMove

代码如下:

namespace Demo1
{
    using System.Drawing;
    using System.Windows.Forms;

    public partial class Form1 : Form
    {
        private Point startPoint;

        public Form1()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Handles the MouseDown event of the Form1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            startPoint = new Point(
                -e.X + SystemInformation.FrameBorderSize.Width, 
                -e.Y - SystemInformation.FrameBorderSize.Height);
        }

        /// <summary>
        /// Handles the MouseMove event of the Form1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Point mousePosition = Control.MousePosition;
                mousePosition.Offset(this.startPoint.X, this.startPoint.Y);
                this.Location = mousePosition;
            }
        }
    }
}

然后你可以试试,这个无边框窗口是可以按住鼠标左键拖拽的。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值