Chansanity

12天前 阅读: 43 点赞: 0 评论: 0

Winform窗体的无边框移动

不知道是哪个大佬的,留作笔记用。

第一步:将下面代码复制到窗体代码中(无需做任何修改)
// 鼠标按下
private bool isMouse = false; // 鼠标是否按下
// 原点位置
private int originX = 0;
private int originY = 0;
// 鼠标按下位置
private int mouseX = 0;
private int mouseY = 0;
private void windowMove_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{ // 判断鼠标按键
isMouse = true;
// 屏幕坐标位置
originX = this.Location.X;
originY = this.Location.Y;
// 鼠标按下位置
mouseX = originX + e.X;
mouseY = originY + e.Y;
}
}    
// 鼠标移动
    private void windowMove_MouseMove(object sender, MouseEventArgs e)
    {
        if (isMouse)
        {
            // 移动距离
            int moveX = (e.X + this.Location.X) - mouseX;
            int moveY = (e.Y + this.Location.Y) - mouseY;
            int targetX = originX + moveX;
            int targetY = originY + moveY;
            this.Location = new Point(targetX, targetY);
        }
    }

    // 鼠标释放
    private void windowMove_MouseUp(object sender, MouseEventArgs e)
    {
        if (isMouse)
        {
            isMouse = false;
        }
    }

第二步:设置窗体的如图三个事件(完事,若窗体上有容器,就设置该容器) image.png