我正在尝试创建一个用户控件,将其拖放到图片框中。
现在,我在网上找到的一些班级的帮助下设法做到了。但是我注意到,当光标位于透明区域时,我可以拖动和移动用户控件,但是当我单击其中的对象时,不能拖动和移动用户控件?还有其他方法吗?
ControlMover.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GridSnap
{
class ControlMover
{
public enum Direction
{
Any,
Horizontal,
Vertical
}
public static void Init(Control control)
{
Init(control, Direction.Any);
}
public static void Init(Control control, Direction direction)
{
Init(control, control, direction);
}
public static void Init(Control control, Control container, Direction direction)
{
bool Dragging = false;
Point DragStart = Point.Empty;
control.MouseDown += delegate (object sender, MouseEventArgs e)
{
Dragging = true;
DragStart = new Point(e.X, e.Y);
control.Capture = true;
};
control.MouseUp += delegate (object sender, MouseEventArgs e)
{
Dragging = false;
control.Capture = false;
};
control.MouseMove += delegate (object sender, MouseEventArgs e)
{
if (Dragging)
{
if (direction != Direction.Vertical)
container.Left = Math.Max(0, e.X + container.Left - DragStart.X);
if (direction != Direction.Horizontal)
container.Top = Math.Max(0, e.Y + container.Top - DragStart.Y);
}
};
}
}
}
Gate.cs(用户控制)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace GridSnap
{
public partial class Gates : UserControl
{
public Gates()
{
InitializeComponent();
GridSnap.ControlMover.Init(this,ControlMover.Direction.Any);
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void Gates_Load(object sender, EventArgs e)
{
}
}
}