2011-03-15 59 views
1

我想拖放绘制在窗体上的图形。这是我绘制矩形的代码。这工作正常。使用绘制矩形拖放功能C#.net - 形式

 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

回答

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#

+1

不错的一个:)我不认为我们可以移动矩形,我们需要一些控制。 – Anuraj 2011-03-15 07:39:20