需求:放在图层上一个图片,要实现鼠标可以选中,并实现拖放功能。
代码实现:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace workflowPro { public partial class Form1 : Form { private int offsetX = 0; private int offsetY = 0; public List<Control> panelControls = new List<Control>(); public Dictionary<Control, List<List<Point>>> rules = new Dictionary<Control, List<List<Point>>>(); public Form1() { InitializeComponent(); PictureBox pictureBox = new PictureBox(); pictureBox.Image = System.Drawing.Bitmap.FromFile(AppDomain.CurrentDomain.BaseDirectory + "\\201208241209467792.png"); pictureBox.Height = 80; pictureBox.Width = 80; pictureBox.MouseDown += mouseDown; pictureBox.MouseUp += mouseUp; pictureBox.MouseMove += mouseMove; panelControls.Add(pictureBox); offsetX = this.panel1.Location.X; offsetY = this.panel1.Location.Y; this.panel1.Controls.Add(pictureBox); } private Point mouseDownPoint = new Point(); private Control selectedControl = new Control(); private Control moveToControl = new Control(); void mouseDown(object sender, MouseEventArgs e) { this.selectedControl = sender as Control; if (e.Button == System.Windows.Forms.MouseButtons.Left) { this.lblPosition.Text = "(" + e.X + "," + e.Y + ")|"; mouseDownPoint = e.Location; } } void mouseMove(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left && this.selectedControl != null) { Point point = this.PointToClient(this.selectedControl.PointToScreen(new Point(e.X - mouseDownPoint.X, e.Y - mouseDownPoint.Y))); this.selectedControl.Location = point; this.selectedControl.Location.Offset(offsetX, -offsetY); this.lblPosition.Text = "|(" + point.X + "," + point.Y + ")"; } } void mouseUp(object sender, MouseEventArgs e) { this.selectedControl = null; } private void MoveToWho(MouseEventArgs e) { foreach (Control control in panelControls) { int x1 = control.Location.X + offsetX; int y1 = control.Location.Y + offsetY; int x2 = x1 + control.Width; int y2 = y1 + control.Height; if (e.X > x1 && e.X < x2 && e.Y > y1 && e.Y < y2) { this.moveToControl = control; } } } } }
时间: 2024-12-14 00:46:11