适用于有标题栏和无标题栏窗体,适用于窗体内控件,当然 Form 也不例外,只要能添加 MouseDown、MouseMove 事件,无需添加 MouseUp 事件,也无需考虑 Form 是否有标题栏。
本方法采用 Control.MousePosition,而没有采用 MouseEventArgs e 获取数据,是因为这样无需考虑窗体有无标题栏和边框的大小,也无需考虑是窗体引发事件,还是窗体内控件引发事件。
代码
// 获取窗体的屏幕坐标和鼠标光标的位置(屏幕坐标)
private void MainForm_MouseDown( object sender, MouseEventArgs e)
{
mousePoint = Control.MousePosition;
formPoint = this .Location;
}
// 鼠标光标的屏幕坐标
Point mousePoint;
// 窗体的屏幕坐标
Point formPoint;
// 响应鼠标移动,并移动窗口
private void MainForm_MouseMove( object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point mousePos = Control.MousePosition;
this .Location = new Point(mousePos.X - mousePoint.X + formPoint.X, mousePos.Y - mousePoint.Y + formPoint.Y);
}
}
// 获取窗体的屏幕坐标和鼠标光标的位置(屏幕坐标)
private void MainForm_MouseDown( object sender, MouseEventArgs e)
{
mousePoint = Control.MousePosition;
formPoint = this .Location;
}
// 鼠标光标的屏幕坐标
Point mousePoint;
// 窗体的屏幕坐标
Point formPoint;
// 响应鼠标移动,并移动窗口
private void MainForm_MouseMove( object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point mousePos = Control.MousePosition;
this .Location = new Point(mousePos.X - mousePoint.X + formPoint.X, mousePos.Y - mousePoint.Y + formPoint.Y);
}
}