C# 实现无标题栏窗口拖动效果
1 /* 首先将窗体的边框样式修改为None,让窗体没有标题栏 2 * 实现这个效果使用了三个事件:鼠标按下、鼠标弹起、鼠标移动 3 * 鼠标按下时更改变量isMouseDown标记窗体可以随鼠标的移动而移动 4 * 鼠标移动时根据鼠标的移动量更改窗体的location属性,实现窗体移动 5 * 鼠标弹起时更改变量isMouseDown标记窗体不可以随鼠标的移动而移动 6 */ 7 private bool isMouseDown = false; 8 private Point FormLocation; //form的location 9 private Point mouseOffset; //鼠标的按下位置 10 private void Form1_MouseDown(object sender, MouseEventArgs e) 11 { 12 if (e.Button == MouseButtons.Left) 13 { 14 isMouseDown = true; 15 FormLocation = this.Location; 16 mouseOffset = Control.MousePosition; 17 } 18 } 19 20 private void Form1_MouseUp(object sender, MouseEventArgs e) 21 { 22 isMouseDown = false; 23 } 24 25 private void Form1_MouseMove(object sender, MouseEventArgs e) 26 { 27 int _x = 0; 28 int _y = 0; 29 if (isMouseDown) 30 { 31 Point pt = Control.MousePosition; 32 _x = mouseOffset.X - pt.X; 33 _y = mouseOffset.Y - pt.Y; 34 35 this.Location = new Point(FormLocation.X - _x, FormLocation.Y - _y); 36 } 37 38 }
工欲善其事,必先利其器。