在.net中实现拖拽控件主要用到以下事件
MouseDown(object sender, MouseEventArgs e)
MouseUp(object sender, MouseEventArgs e)
MouseMove(object sender, MouseEventArgs e)
这三个函数的作用分别是鼠标按下时激活,鼠标松开激活和鼠标移动
需要考虑的情况如下
1. 只有在鼠标按下的时候才可以使用鼠标移动事件
2. 鼠标移动的时候控件重新调整位置
为了有效控制第一个条件,所以可以将鼠标移动事件的绑定推迟到鼠标按下事件中,而不是在初始化时完成,另外要记录下初始状态下鼠标位于控件中的坐标,这里注意MouseEventArgs参数中的X,Y表示的是鼠标在当前控件中的layout坐标,而不是鼠标在主窗口中的坐标。
rivate void button1_MouseDown(object sender, MouseEventArgs e)
{
this.tmpx = e.X;
this.tmpy = e.Y;
this.button1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.button1_MouseMove);
}
同时在鼠标送开事件中再将该方法绑定脱离
private void button1_MouseUp(object sender, MouseEventArgs e)
{
this.button1.MouseMove -= new System.Windows.Forms.MouseEventHandler(this.button1_MouseMove);
}
最后是MouseMove事件
private void button1_MouseMove(object sender, MouseEventArgs e)
{
this.button1.Location = new System.Drawing.Point(this.button1.Location.X + e.X - this.tmpx, this.button1.Location.Y + e.Y - this.tmpy);
}
这里重新计算了控件的新位置。
例子中使用了button作为实验对象并且额外定义了
private int tmpx = 0;
private int tmpy = 0;
private int tmpx = 0; private int tmpy = 0; private void panel1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { this.tmpx = e.X; this.tmpy = e.Y; this.panel1.Cursor = Cursors.SizeAll; this.panel1.MouseMove += new MouseEventHandler(panel1_MouseMove); } } private void panel1_MouseUp(object sender, MouseEventArgs e) { this.panel1.Cursor = Cursors.Default; this.panel1.MouseMove -= new MouseEventHandler(panel1_MouseMove); } void panel1_MouseMove(object sender, MouseEventArgs e) { this.panel1.Location = new Point(this.panel1.Location.X + e.X - this.tmpx, this.panel1.Location.Y + e.Y - this.tmpy); }