1//记录鼠标指针的坐标
2private Point mouseOffset;
3
4//记录鼠标按键是否按下
5private bool isMouseDown = false;
6
7private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
8 {
9 int xOffset;
10 int yOffset;
11
12 if (e.Button == MouseButtons.Left)
13 {
14 xOffset = -e.X - SystemInformation.FrameBorderSize.Width;
15
16 yOffset = -e.Y - SystemInformation.CaptionHeight -
17
18 SystemInformation.FrameBorderSize.Height;
19
20 mouseOffset = new Point(xOffset, yOffset);
21
22 isMouseDown = true;
23 }
24 }
25
26 private void Form1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
27 {
28 if (isMouseDown)
29 {
30 Point mousePos = Control.MousePosition;
31 mousePos.Offset(mouseOffset.X, mouseOffset.Y);
32 Location = mousePos;
33 }
34 }
35
36 private void Form1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
37 {
38 // 修改鼠标状态isMouseDown的值
39 // 确保只有鼠标左键按下并移动时,才移动窗体
40 if (e.Button == MouseButtons.Left)
41 {
42 isMouseDown = false;
43 }
44 }
2private Point mouseOffset;
3
4//记录鼠标按键是否按下
5private bool isMouseDown = false;
6
7private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
8 {
9 int xOffset;
10 int yOffset;
11
12 if (e.Button == MouseButtons.Left)
13 {
14 xOffset = -e.X - SystemInformation.FrameBorderSize.Width;
15
16 yOffset = -e.Y - SystemInformation.CaptionHeight -
17
18 SystemInformation.FrameBorderSize.Height;
19
20 mouseOffset = new Point(xOffset, yOffset);
21
22 isMouseDown = true;
23 }
24 }
25
26 private void Form1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
27 {
28 if (isMouseDown)
29 {
30 Point mousePos = Control.MousePosition;
31 mousePos.Offset(mouseOffset.X, mouseOffset.Y);
32 Location = mousePos;
33 }
34 }
35
36 private void Form1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
37 {
38 // 修改鼠标状态isMouseDown的值
39 // 确保只有鼠标左键按下并移动时,才移动窗体
40 if (e.Button == MouseButtons.Left)
41 {
42 isMouseDown = false;
43 }
44 }