代码如下:
1 private Point mouseOff;//鼠标移动位置变量 2 private bool leftFlag;//标签是否为左键 3 private void FrmMain_MouseDown(object sender, MouseEventArgs e) 4 { 5 if (e.Button == MouseButtons.Left) 6 { 7 mouseOff = new Point(-e.X, -e.Y); //得到变量的值 8 leftFlag = true; //点击左键按下时标注为true; 9 } 10 } 11 private void FrmMain_MouseMove(object sender, MouseEventArgs e) 12 { 13 if (leftFlag) 14 { 15 Point mouseSet = Control.MousePosition; 16 mouseSet.Offset(mouseOff.X, mouseOff.Y); //设置移动后的位置 17 Location = mouseSet; 18 } 19 } 20 private void FrmMain_MouseUp(object sender, MouseEventArgs e) 21 { 22 if (leftFlag) 23 { 24 leftFlag = false;//释放鼠标后标注为false; 25 } 26 }
需要在哪个控件上实现这个功能,就在控件添加上这三个事件就好了。