鼠标按下时如何移动窗口

ped*_*ram 4 c# winforms

当我们在标题栏上鼠标按下时,我们能够移动窗体.但是当鼠标按下形式时如何移动窗口?

djd*_*d87 11

您需要使用MouseDownMouseUp事件记录鼠标何时向下和向上:

private bool mouseIsDown = false;
private Point firstPoint;

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    firstPoint = e.Location;
    mouseIsDown = true;
}

private void Form1_MouseUp(object sender, MouseEventArgs e)
{
    mouseIsDown = false;
}
Run Code Online (Sandbox Code Playgroud)

如您所见,第一点正在被记录,因此您可以MouseMove按如下方式使用该事件:

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (mouseIsDown)
    {
        // Get the difference between the two points
        int xDiff = firstPoint.X - e.Location.X;
        int yDiff = firstPoint.Y - e.Location.Y;

        // Set the new point
        int x = this.Location.X - xDiff;
        int y = this.Location.Y - yDiff;
        this.Location = new Point(x, y);
    }
}
Run Code Online (Sandbox Code Playgroud)