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

有时候,为了达到一些特定的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;
            }
        }
    }
}

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


你可能感兴趣的:(.net,windows,form,C#)