鼠标拖拽效果的实现
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
首先在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
相关文章推荐
- 实现一个宽和高都是100像素的div可以用鼠标拖拽移动的效果
- 使用b2MouseJoint实现鼠标拖拽刚体的效果
- Wince中为元件注册鼠标事件以实现Canvas中的拖拽效果
- jquery实现鼠标拖拽滑动效果来选择数字的方法
- 实现鼠标的拖拽效果 by johannes
- jq实现鼠标拖拽效果
- 利用canvas实现鼠标拖拽效果的一种方法
- 鼠标拖拽效果原理及完整代码实现
- jQuery实现鼠标拖拽div效果
- 超酷的鼠标拖拽翻页(分页)效果实现javascript代码
- 基于jquery实现的鼠标拖拽元素复制并写入效果
- js实现百度登录框鼠标拖拽效果
- JavaScript实现鼠标拖拽效果
- PyQt5学习记录(7)---监听鼠标拖拽事件实现Mac上百度云盘拖拽效果
- 基于jquery实现的鼠标拖拽元素复制并写入效果
- js实现简单鼠标拖拽,文件拖入文件夹效果
- jquery实现鼠标拖拽滑动效果来选择数字的方法
- js实现登录框鼠标拖拽效果
- Jquery实现鼠标拖拽效果