在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(mX, mY,100,100); drag = true; cur_x = mX; cur_y = mY; } private void recmousemove(object sender, MouseEventArgs m) { if (m.Button != MouseButtons.Left) return; rec.X = mX; rec.Y = mY; Invalidate(); } } 

你非常接近,你只需要更好地初始化矩形并在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(eX, eY, 0, 0); Invalidate(); } } protected override void OnMouseMove(MouseEventArgs e) { if (e.Button == MouseButtons.Left) { rec.Width = eX - rec.X; rec.Height = eY - rec.Y; Invalidate(); } } } 

您可以尝试本文中的方法: http : //beta.codeproject.com/KB/GDI-plus/flickerFreeDrawing.aspx