Drag and drop rectangle in C#

后端 未结 2 1760
广开言路
广开言路 2021-01-15 09:54

I want to know how to draw rectangle in C# and make it dragged and dropped in the page here my code to draw it but I cannot drag or drop it.

public partial c         


        
相关标签:
2条回答
  • 2021-01-15 10:40

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

    0 讨论(0)
  • 2021-01-15 10:52

    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();
          }
        }
      }
    
    0 讨论(0)
提交回复
热议问题