2010-03-14 109 views
2

我想知道如何在C#中繪製矩形,並將其拖放到頁面中的這裏我的代碼來繪製它,但我不能拖放它。在C中拖放矩形#

public partial class Form1 : Form 
{ 
    public bool drag = false; 
    int cur_x, cur_y; 
    Rectangle rec = new Rectangle(10, 10, 100, 100); 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    protected override void OnPaint(PaintEventArgs r) 
    { 
     base.OnPaint(r); 
     Graphics g = r.Graphics; 
     //g.DrawRectangle(Pens.Black, rec); 
     g.FillRectangle(Brushes.Aquamarine, rec); 

    } 
    private void recmousedown(object sender, MouseEventArgs m) 
    { 
     if (m.Button != MouseButtons.Left) 
      return; 
     rec = new Rectangle(m.X, m.Y,100,100); 

     drag = true; 
     cur_x = m.X; 
     cur_y = m.Y; 
    } 

    private void recmousemove(object sender, MouseEventArgs m) 
    { 
     if (m.Button != MouseButtons.Left) 
      return; 

     rec.X = m.X; 
     rec.Y = m.Y; 
     Invalidate(); 
    } 
} 
+0

我想你需要在這裏詳細說一下你的意思是「拖放」:使用繪畫的技巧將產生一次性的矩形,在下一次MouseDown中通過調用Invalidate來清除。你正在尋找一個矩形,或矩形,將「堅持」在屏幕上?那麼你可以「選擇」並移動,或調整大小? – BillW 2010-03-14 15:46:46

+0

如果你需要「形狀」檢查這個當前的SO問題:http://stackoverflow.com/questions/2440912/visual-studio-adding-ovalshape-and-rectangleshape-tool-references-to-a-project – BillW 2010-03-14 15:51:22

回答

6

你很接近,你只需要初始化矩形更好,調整Move事件矩形大小:

public partial class Form1 : Form { 
    public Form1() { 
     InitializeComponent(); 
     this.DoubleBuffered = true; 
    } 
    Rectangle rec = new Rectangle(0, 0, 0, 0); 

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