How to draw and move shapes using mouse in C#

后端 未结 2 1690
庸人自扰
庸人自扰 2020-12-30 15:49

I\'m new to programming in C# and wanted to ask for a little bit of help. I\'m currently trying to move a color-filled rectangle that I draw on a Windows Application form wi

相关标签:
2条回答
  • 2020-12-30 16:32

    This seems to work

        protected override void OnMouseMove(MouseEventArgs e)
        {
    
    
            if (e.Button == MouseButtons.Left)
            {
                rec.Width = e.X - rec.X;
                rec.Height = e.Y - rec.Y;
                this.Invalidate();
            }
    
            if (e.Button == MouseButtons.Right)
            {
                rec.Location = new Point((e.X-MouseDownLocation.X) + rec.Left, (e.Y-MouseDownLocation.Y) + rec.Top);
                MouseDownLocation = e.Location;
                this.Invalidate();
            }
        }
    
    0 讨论(0)
  • 2020-12-30 16:49

    try this one : Notice that I add timer to the form in this method you don't need to call Invalidate on mouse event the timertick is calling to the Refresh() so the form will paint himself in each tick..

    public partial class Form1 : Form
    {
       private Point MouseDownLocation;
    
       public Form1()
       {
          InitializeComponent();
          this.DoubleBuffered = true;
          timer1.Start(); // add timer to the form
       }
       Rectangle rec = new Rectangle(0, 0, 0, 0);
    
       protected override void OnPaint(PaintEventArgs e)
       {
           e.Graphics.FillRectangle(Brushes.DeepSkyBlue, rec);
       }
    
       private void timer1_Tick(object sender, EventArgs e)
       {
           Refresh();
       }
    
    
      protected override void OnMouseMove(MouseEventArgs e)
      {
          if (e.Button == MouseButtons.Left)
          {
             rec.Width = e.X - rec.X;
             rec.Height = e.Y - rec.Y;
          }
          else if (e.Button == MouseButtons.Right)
          {
            rec.X = e.X - MouseDownLocation.X;
            rec.Y = e.Y - MouseDownLocation.Y;
          }
      }
    
       protected override void OnMouseUp(object sender, MouseEventArgs e)
       {
           if (e.Button == MouseButtons.Right)
              MouseDownLocation = e.Location;
       }
     }
    
    0 讨论(0)
提交回复
热议问题