c# 鼠标点击控件即拖动窗体

 在编程中,有时打开的窗体没有边框,但是我们仍然想在鼠标放在窗体上就能拖动窗体,这样我们只需要以窗体中的一个控件为参考,我们在这里以panel为例子:

    public class PanelNew : PanelEx
    {
        private Point CPoint = new Point();
        protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e)
        {
            CPoint.X = -e.X;
            CPoint.Y = -e.Y;
            base.OnMouseDown(e);
        }
        protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs e)
        {
            if (this.Parent is Form)
            {
                if (e.Button == MouseButtons.Left)
                {
                    Point myPosittion = Control.MousePosition;//获取当前鼠标的屏幕坐标 
                    myPosittion.Offset(CPoint.X, CPoint.Y);//重载当前鼠标的位置 
                    (this.Parent as Form).DesktopLocation = myPosittion;//设置当前窗体在屏幕上的位置 
                }
            }
            base.OnMouseMove(e);
        }
    }
View Code

我在这里是直接创建了一个新的控件,如果直接在窗体的控件上操作,只需要在控件相应的事件中填入代码就行了。

原文地址:https://www.cnblogs.com/sczmzx/p/3370959.html