Dear Friends!
I want to draw a bouncing ball directly on form using component timer.
I think that I should draw a ball then change its coordinates. Like this:

public partial class FormMain : Form
    {   int mx = 10;
        int my = 10;
        public FormMain()
        {
            InitializeComponent();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            System.Drawing.Graphics graphicsObj;
            graphicsObj = this.CreateGraphics();
            Pen myPen = new Pen(System.Drawing.Color.Green, 5);
            mx += 10; my += 10;
            Rectangle myRectangle = new Rectangle(mx, my, 10, 10);
            //graphicsObj.DrawEllipse(myPen, myRectangle);
            graphicsObj.FillEllipse(new SolidBrush(Color.Blue), myRectangle);
            
        }
     }

It's working incorrectly so I really need your help.
Thanks in advanced for any suggestion.

Edited 6 Years Ago by svatstika: n/a

I am sure you know already that if you wish to simulate a bouncing ball then you will need to do more than +10 to the coordinates.

The correct way to draw to a form is to use the Paint event.
Use the timer to adjust the coordinates and use the paint event to draw the object(s) on the form.

This should get you started.

public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        int mx = 10;
        int my = 10;

        private void timer1_Tick(object sender, EventArgs e)
        {
            mx += 10; my += 10; //<-- must change this to get "ball bounce" 
            this.Invalidate(); //<-- needed to cause form to update.
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            System.Drawing.Graphics graphicsObj = e.Graphics;
            Pen myPen = new Pen(System.Drawing.Color.Green, 5);
            Rectangle myRectangle = new Rectangle(mx, my, 10, 10);
            //graphicsObj.DrawEllipse(myPen, myRectangle);
            graphicsObj.FillEllipse(new SolidBrush(Color.Blue), myRectangle);

            // allow form to do its thing
            base.OnPaint(e);
        }
    }

Edited 6 Years Ago by nick.crane: n/a

This article has been dead for over six months. Start a new discussion instead.