C#Winform窗口移动

在我们将Winform自带的边框隐藏之后,我们需要自己编写窗口的移动。
思路就是1.获得点击左键时当前鼠标的坐标 2.获得移动后鼠标的坐标 3.窗体的坐标=移动后的鼠标坐标-移动前的鼠标坐标

private Point mouseOff;//鼠标移动位置变量
        private bool leftFlag;//鼠标是否为左键
        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            if(e.Button == MouseButtons.Left)
            {
                mouseOff = new Point(-e.X, -e.Y);//获得当前鼠标的坐标
                leftFlag = true;
            }
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (leftFlag)
            {
                Point mouseSet = Control.MousePosition;//获得移动后鼠标的坐标
                mouseSet.Offset(mouseOff.X, mouseOff.Y);//设置移动后的位置
                Location = mouseSet;
            }
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            if (leftFlag)
            {
                leftFlag = false;
            }
        }

猜你喜欢

转载自blog.csdn.net/Maybe_ch/article/details/81482054