Drag and drop rectangle in C#

吃可爱长大的小学妹 提交于 2019-12-01 11:17:12

You're pretty close, you just need to initialize the rectangle better and adjust the rectangle size in the Move event:

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

You could try the approach in this article: http://beta.codeproject.com/KB/GDI-plus/flickerFreeDrawing.aspx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!