Make a borderless form movable?

前端 未结 21 2145
情歌与酒
情歌与酒 2020-11-22 09:48

Is there a way to make a form that has no border (FormBorderStyle is set to \"none\") movable when the mouse is clicked down on the form just as if there was a border?

21条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 10:22

    I'm expanding the solution from jay_t55 with one more method ToolStrip1_MouseLeave that handles the event of the mouse moving quickly and leaving the region.

    private bool mouseDown;
    private Point lastLocation;
    
    private void ToolStrip1_MouseDown(object sender, MouseEventArgs e) {
        mouseDown = true;
        lastLocation = e.Location;
    }
    
    private void ToolStrip1_MouseMove(object sender, MouseEventArgs e) {
        if (mouseDown) {
            this.Location = new Point(
                (this.Location.X - lastLocation.X) + e.X, (this.Location.Y - lastLocation.Y) + e.Y);
    
            this.Update();
        }
    }
    
    private void ToolStrip1_MouseUp(object sender, MouseEventArgs e) {
        mouseDown = false;
    }
    
    private void ToolStrip1_MouseLeave(object sender, EventArgs e) {
        mouseDown = false;
    }
    

提交回复
热议问题