鼠标按下时如何移动窗口

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

您需要使用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; } 

如您所见,第一个点正在被记录,因此您可以使用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); } } 

您可以通过处理MouseDown事件手动执行此操作,如其他答案中所述。 另一个选择是使用我前一段时间写的这个小实用程序类 。 它允许您自动使窗口“可移动”,而无需一行代码。

当鼠标按钮在窗体中向下移动时监听事件,然后听取鼠标移动直到它再次上升。

这是一篇代码项目文章,展示了如何执行此操作: 在C#中移动没有Titlebar的窗口/表单