使用绘图矩形C#.net - 表单拖放功能

时间:2011-03-15 05:42:04

标签: c# drag-and-drop system.drawing windows-forms-designer

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

        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

1 个答案:

答案 0 :(得分:2)

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

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);  

嗯,你没有控制权。这是一个矩形。但希望你能得到这个想法 更新:您是否查看了此页面中列出的相关问题?尝试:
Drag and drop rectangle in C#