Hello! I just started to deal with C #, I want to draw a moving circle. Wrote such methods:

private void draw() { Pen myPen = new Pen(Color.Black); g.DrawRectangle(myPen, 10, 10, 50, 50); g.DrawEllipse(myPen, (float)xStart, (float)yStart, 5, 5); } private void updateCoords(object obj) { if (xStart < 10) dx = -dx; if (xStart > 60) dx = -dx; if (yStart < 10) dy = -dy; if (yStart > 60) dy = -dy; xStart = xStart + dx; yStart = yStart + dy; draw(); } private void button1_Click(object sender, EventArgs e) { int time = 0; TimerCallback tc = new TimerCallback(updateCoords); System.Threading.Timer timer = new System.Threading.Timer(tc, ++time, 0, 100); } 

When I press a button, the circle starts moving, but every time it is drawn again, the old circles do not disappear, i.e. many circles displayed at once. Tell me, please, how to make it so that at each moment only one circle is displayed in the current position. I use Visual Studio 2015.

Added by

 Graphics g; // определяется в классе, но снаружи методов public Form1() // есть у меня такой метод ещё { InitializeComponent(); g = panel1.CreateGraphics(); } 
  • one
    paint over an old circle or the whole canvas. What is g ? - Igor
  • one
    Make your component, override the OnRender() method or something like that. - LLENN
  • Thank! Painting the old circle helped, that is, this option is suitable. Now I will try to override the OnRender () method. - ⷶ ⷩ ⷮ ⷪ ⷩ
  • one
    The method in WinForm is called OnPaint() - LLENN

1 answer 1

As an example, here is a class for you, but naturally it is necessary to remake it for yourself.

 using System.Drawing; using System.Windows.Forms; public class MyPainter : Control { private int _xStart, _yStart, _dx, _dy; private readonly System.Threading.Timer _timer; public MyPainter() { int time = 0; _timer = new System.Threading.Timer(UpdateCoords, ++time, 0, 100); } ~MyPainter() { _timer?.Dispose(); } public void UpdateCoords(object obj) { _dx--; _dy--; if (_xStart < 10) _dx = -_dx; if (_xStart > 60) _dx = -_dx; if (_yStart < 10) _dy = -_dy; if (_yStart > 60) _dy = -_dy; _xStart = _xStart + _dx; _yStart = _yStart + _dy; Invalidate(); } protected override void OnPaint(PaintEventArgs e) { e.Graphics.DrawRectangle(Pens.White, new Rectangle(0, 0, Size.Width, Size.Height)); e.Graphics.DrawRectangle(Pens.Black, 10, 10, 50, 50); e.Graphics.DrawEllipse(Pens.Black, new Rectangle(_xStart, _yStart, 40, 40)); } } 
  • Thank! Now I sort of understand what to do. - ⷶ ⷩ ⷮ ⷪ ⷩ