需求:放在图层上一个图片,要实现鼠标可以选中,并实现拖放功能。
需求分析:
1、采用winform方式实现;
2、需要一个PictureBox对象,对该PictureBox添加MouseMove,MouseDown,MouseUp事件。
3、MouseDown事件中:当鼠标在PictureBox对象中左键按下时,记录下鼠标相对PictureBox左上角的坐标点mouseDownPoint;
4、MouseMove事件中:先获取到当前鼠标所在位置,并减去鼠标左键按下时相对PictureBox左上角的坐标点,就是当前坐标要停留的坐标点位置。
在vs2010创建winform project,设置窗体如下:
运行结果:
实现代码:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 10 namespace workflowPro11 {12 public partial class Main : Form13 {14 public Main()15 {16 InitializeComponent();17 18 // 生成一个PictureBox对象19 PictureBox pictureBox = new PictureBox();20 pictureBox.Image = System.Drawing.Bitmap.FromFile(AppDomain.CurrentDomain.BaseDirectory + "\\a307536.gif");21 pictureBox.Height = 80;22 pictureBox.Width = 80;23 24 // 给PictureBox控件添加MouseDown/MouseUp/MouseMove事件25 pictureBox.MouseDown += mouseDown;26 pictureBox.MouseUp += mouseUp;27 pictureBox.MouseMove += mouseMove;28 29 // 把PictureBox对象添加到Panel图层中。30 this.panelWork.Controls.Add(pictureBox);31 }32 33 // 存储当鼠标在PictureBox中左键按下的位置,相对于PictureBox左上角坐标点的位置来讲。34 private Point mouseDownPoint = new Point();35 // 就当前被操作的对象,实际上这里也可以不记录,统一使用事件中的sender对象转化。36 private Control selectedControl = new Control();37 38 ///39 /// 当鼠标在PictureBox范围内,并且按下左键时,记录鼠标相对于PictureBox左上角坐标点的位置(相对PictureBox的坐标点)。40 /// 41 /// 42 /// 43 void mouseDown(object sender, MouseEventArgs e)44 {45 this.selectedControl = sender as Control;46 47 if (e.Button == System.Windows.Forms.MouseButtons.Left)48 {49 this.lblPosition.Text = "(" + e.X + "," + e.Y + ")|";50 51 mouseDownPoint = e.Location;52 }53 }54 55 void mouseMove(object sender, MouseEventArgs e)56 {57 if (e.Button == System.Windows.Forms.MouseButtons.Left && this.selectedControl != null)58 {59 // 先获取到当前鼠标所在位置,并减去鼠标左键按下时相对PictureBox左上角的坐标点,就是当前坐标要停留的坐标点位置。60 Point point = this.PointToClient(this.selectedControl.PointToScreen(new Point(e.X - mouseDownPoint.X, e.Y - mouseDownPoint.Y)));61 this.selectedControl.Location = point;62 63 this.lblPosition.Text = "|(" + point.X + "," + point.Y + ")";64 }65 }66 67 void mouseUp(object sender, MouseEventArgs e)68 {69 this.selectedControl = null;70 }71 }72 }
参考文章:
http://www.cnblogs.com/huaisha/archive/2013/03/24/2978145.html