1

我有一个 WinForms Forma UserControl,其中多个实例可以动态创建。如果我选择它,我可以拖动它。现在,如果我选择多个用户控件(ctrl单击 + 按钮),我希望能够同时拖动所有这些控件。

我可以像对一个 UserControl 那样做吗?

我到目前为止所尝试的:

// 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();
            }
        }
    }
}
4

2 回答 2

3

// 将您的控件放在面板中,并使用此类。

  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);
    }
于 2013-05-01T08:17:30.203 回答
2

如果您希望程序在按下 ctrl + 键时激活,那么您需要查看键挂钩,然后在按键事件中设置一些代码,告诉程序选择所有项目。如果您是 key hooks 的新手,这是非常高级且难以做到的,但这里有一个 key hooks 的链接。祝你好运!

http://www.codeproject.com/Articles/19004/A-Simple-C-Global-Low-Level-Keyboard-Hook

于 2013-05-01T07:55:50.570 回答