问题
I have on a WinForms Form a UserControl, of which multiple instances can be created dynamically. If I select it, I can drag it. Now, I want, if I select multiple UserControls (with ctrl + button click), to be able to drag all of them at the same time.
Can I do that like I did for one UserControl?
What I have tried until now:
// For dragging I use this method and also I have
// overridden MouseUp,MouseDown,MouseMove from .net
public void StartDrag()
{
dragging = true;
Point p = PointToClient(Cursor.Position);
dragStart = new Point(Math.Max(0, p.X), Math.Max(0, p.Y));
buttondrag.Capture = true;
}
private void Usercontrol1_SelectedChanged(object sender, EventArgs e)
{
if (((UserControl)sender).Selected)
{
if (SelectedUserControl.Count > 1)
{
foreach (UserControl c in panel1.Controls)
{
c.StartDrag();
}
}
}
}
回答1:
// put your controls in the panel, and use this class.
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);
}
};
}
}
public Form1()
{
InitializeComponent();
ControlMover.Init(this.panel1);
ControlMover.Init(this.panel1, ControlMover.Direction.Vertical);
}
回答2:
If you want the program to activate when ctrl + key is pressed then you will need to look at key hooks, and then set up some code in the key down event telling the program to select all items. This is quite advanced and difficult to do if your new to key hooks, but here's a link for key hooks. Good luck!
http://www.codeproject.com/Articles/19004/A-Simple-C-Global-Low-Level-Keyboard-Hook
来源:https://stackoverflow.com/questions/16314410/drag-multiple-selected-controls