您的位置:首页 > 其它

鼠标拖拽效果的实现

2013-03-24 09:40 489 查看
我所说的“鼠标拖拽效果”是指,鼠标在某个图标上按下,然后拖动,图标随着鼠标移动;这个效果的实现依赖控件的三个事件:Mouse_Down,Mouse_Move,Mouse_Up

首先在Mouse_Down事件设置”拖动”标志,表明鼠标已经按下,将要移动;同时记录鼠标的起始位置

然后在Mouse_Move事件计算鼠标的新位置,将图标设置到鼠标的位置,重新绘图

最后在Mouse_Up事件关闭”拖动”标志,标志鼠标已经弹起

实现如下:

首先,在Visual Studio 2010创建一个“Windows窗体应用程序”项目,在Form上任意拖入一个控件(比如Button,Label等,为了看得明白,我这里拖入的是PictureBox控件),为PictureBox的Image属性设置图片,效果如下:

View Code

#region Events

//PictureBox.Click事件
private void pbxDrag_Click(object sender, EventArgs e)
{
//0.取控件实例
var pbxDrag = sender as PictureBox;

//1.用边框模拟选中状态
pbxDrag.BorderStyle = BorderStyle.FixedSingle;
}

//PictrueBox.MouseDown事件(鼠标在控件上按下左键触发)
private void pbxDrag_MouseDown(object sender, MouseEventArgs e)
{
//0.取控件实例
var pbxDrag = sender as PictureBox;

//1.设置"拖动"标识
this.m_bDragFlag = true;

//2.设置鼠标形状
this.Cursor = Cursors.SizeAll;

//3.设置初始位置
this.m_oStartLocation = pbxDrag.Location;
}
//PictureBox.MouseMove事件(鼠标在控件上移动后触发)
private void pbxDrag_MouseMove(object sender, MouseEventArgs e)
{
//0.取控件实例
var pbxDrag = sender as PictureBox;

if (this.m_bDragFlag)
{
//1.设置鼠标形状
this.Cursor = Cursors.Default;

//2.设置控件新位置
pbxDrag.Location = new Point(this.m_oStartLocation.X + e.X, this.m_oStartLocation.Y + e.Y);

//3.重新绘制图形
this.Invalidate();
this.Update();

//4.修正位置
this.m_oStartLocation = pbxDrag.Location;
}
}
//PictureBox.MouseUp事件(鼠标在控件上弹起时触发)
private void pbxDrag_MouseUp(object sender, MouseEventArgs e)
{
//0.设置鼠标形状
this.Cursor = Cursors.Default;

//1.设置"拖动"标识
this.m_bDragFlag = false;
}

#endregion
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: