2011-03-15 3 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(); 
      } 
     } 

는 지금은 드래그하고 다른 장소에서 그 사각형을 드롭합니다. 그런 다음

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

난 그냥 그것을 초기화 :

Pls는이

당신에게 내가 이런 종류의 물건에 대한 헬퍼 클래스를 작성했습니다

답변

2

요한 감사 것을 수행하는 방법에 도움이 내 양식로드 이벤트 :

ControlMover.Init(myControl, myContainer, ControlMover.Direction.Any); 

글쎄, 이동할 권한이 없습니다. 그것은 직사각형입니다. 그러나 잘하면, 당신은 아이디어를 얻을 것이다.
업데이트 :이 페이지에 나열된 관련 질문을 확인하셨습니까? 시도해보십시오 :
Drag and drop rectangle in C#

+1

좋은 1 : 나는 우리가 사각형을 이동할 수 있다고 생각지 않아, 우리는 약간의 통제가 필요합니다. – Anuraj