效果是这个样子
只要鼠标放在按钮上,点击一下,之后按钮就会一直跟随按钮移动,或者鼠标必须一直按下,按钮才会一直跟随鼠标移动。
namespace demo3
{
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}
private void Form4_Load(object sender, EventArgs e)
{
//订阅鼠标移动的事件,鼠标只需要按下一次就可以一直移动
button1.MouseDown += new MouseEventHandler(mouseDown);
}
public void mouseDown(object o,MouseEventArgs e)
{
DoDragDrop(o, DragDropEffects.Move);
}
private bool isMouseDown = false;
private Point bLocation;
private Point offsetMouseLocation;
private void button1_MouseDown(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Left)
{
isMouseDown = true;
//记录组件的原始位置
bLocation = ((Button)sender).Location;
//记录鼠标的原始位置
offsetMouseLocation = Control.MousePosition;
}
}
private void button1_MouseUp(object sender, MouseEventArgs e)
{
isMouseDown = false;
}
private void button1_MouseMove(object sender, MouseEventArgs e)
{
Point point = Control.MousePosition; //鼠标新的位置
if (isMouseDown)
{
//组件新的位置 = 组件原来的位置-鼠标移动的位置
//鼠标移动的位置 = 鼠标原来的位置-鼠标最终的位置
((Button)sender).Location =
new Point(bLocation.X - (offsetMouseLocation.X - point.X),
bLocation.Y - (offsetMouseLocation.Y - point.Y));
}
}
}
}