当我们在标题栏上鼠标按下时,我们可以移动窗体。 但是当鼠标按下形式时如何移动窗口?
答案 0 :(得分:11)
您需要使用MouseDown
和MouseUp
事件记录鼠标何时停止运行:
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);
}
}
答案 1 :(得分:4)
您可以通过处理MouseDown
事件手动执行此操作,如其他答案中所述。另一个选择是使用我前一段时间写的这个small utility class。它允许您自动使窗口“可移动”,而无需一行代码。
答案 2 :(得分:3)
当鼠标按钮在窗体中向下移动时监听事件,然后听取鼠标移动直到它再次上升。
这是一篇代码项目文章,展示了如何执行此操作:Move window/form without Titlebar in C#
答案 3 :(得分:0)
您不能使用MouseUp或Down中提供的位置,您应该使用这样的系统位置
private Point diffPoint;
bool mouseDown = false;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
//saves position difference
diffPoint.X = System.Windows.Forms.Cursor.Position.X - this.Left;
diffPoint.Y = System.Windows.Forms.Cursor.Position.Y - this.Top;
mouseDown = true;
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
mouseDown = false;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (mouseDown)
{
this.Left = System.Windows.Forms.Cursor.Position.X - diffPoint.X;
this.Top = System.Windows.Forms.Cursor.Position.Y - diffPoint.Y;
}
}
这可以通过测试。