具有绘制矩形C#.net的拖放功能-表单

具有绘制矩形C#.net的拖放功能-表单,c#,drag-and-drop,system.drawing,windows-forms-designer,C#,Drag And Drop,System.drawing,Windows Forms Designer,我想拖放我在表单上绘制的内容。这是我绘制矩形的代码。A这个很好用 Rectangle rec = new Rectangle(0, 0, 0, 0); public Form1() { InitializeComponent(); this.DoubleBuffered = true; } protected override void OnPaint(PaintE

我想拖放我在表单上绘制的内容。这是我绘制矩形的代码。A这个很好用

        Rectangle rec = new Rectangle(0, 0, 0, 0);

        public Form1()
        {
            InitializeComponent();
            this.DoubleBuffered = true;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            e.Graphics.FillRectangle(Brushes.Aquamarine, rec);
        }
        protected override void OnMouseDown(MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                rec = new Rectangle(e.X, e.Y, 0, 0);
                Invalidate();
            }
        }
        protected override void OnMouseMove(MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                rec.Width = e.X - rec.X;
                rec.Height = e.Y - rec.Y;
                Invalidate();
            }
        }
现在我想把那个矩形拖放到另一个地方

请帮忙怎么做

多谢各位


yohan

我为这类东西编写了一个助手类:

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);
            }
        };
    }
}  
然后,我只需在我的窗体加载事件中使用我的控件初始化它:

ControlMover.Init(myControl, myContainer, ControlMover.Direction.Any);  
嗯,你无法控制移动。它是一个长方形。但希望你能明白这一点。
更新:您是否查看了本页中列出的相关问题?试试看:

Nice one:)我想我们不能移动矩形,我们需要一些控制。