首页 > 代码库 > WinForm 之 自定义标题栏的窗体移动

WinForm 之 自定义标题栏的窗体移动

  通过标题栏的鼠标事件实现窗体移动,代码如下:

        bool m_isMouseDown = false; //窗体是否移动
        Point m_mousePos; //记录窗体的位置
        /// <summary>
        /// 鼠标按下,开启移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panelTitle_MouseDown(object sender, MouseEventArgs e)
        {
            m_mousePos = Cursor.Position;
            m_isMouseDown = true;
        }

        /// <summary>
        /// 窗体鼠标移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panelTitle_MouseMove(object sender, MouseEventArgs e)
        {
            if (m_isMouseDown)
            {
                Point tempPos = Cursor.Position;
                this.Location = new Point(Location.X + (tempPos.X - m_mousePos.X), Location.Y + (tempPos.Y - m_mousePos.Y));
                m_mousePos = Cursor.Position;
            }
        }

        /// <summary>
        /// 鼠标抬起,关闭移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panelTitle_MouseUp(object sender, MouseEventArgs e)
        {
            m_isMouseDown = false;
            this.Focus();
        }

 

WinForm 之 自定义标题栏的窗体移动