TarunG TarunG - 2 months ago 22
C# Question

Understanding a small c# code snippet involving paint()

I am new to c#(using visual c# 2010), and was tying to make a simple game, it will have bouncing ball type thing,

I used graphics fillellipse to make a ball, now i have this code with me,

protected override void OnPaint( PaintEventArgs e)
//System.Drawing.Graphics gobj;
gobj = this.CreateGraphics();
Pen pen = new Pen(System.Drawing.Color.LightSkyBlue, 6);
SolidBrush brush = new SolidBrush(System.Drawing.Color.Magenta);
Rectangle myRectangle = new Rectangle((PointToClient(Cursor.Position).X), PointToClient(Cursor.Position).Y, 250, 200);

gobj.DrawRectangle(pen, myRectangle);
gobj.FillEllipse(brush, myRectangle);

when i run this code, i keep on getting many circles and rectangles, popping under a section of screen only, but shouldn't it draw just a single circle??

Please help me understand this??


You drawing rectangle with DrawRectangle method and then circle with FillEllipse, you need to use just FillEllipse. And like Mikant mentioned you don't need to create graphics - use e.Graphics. Here is code:

protected override void OnPaint(PaintEventArgs e)
    SolidBrush brush = new SolidBrush(System.Drawing.Color.Magenta);
    e.Graphics.FillEllipse(brush, (this.Height / 2) - 40, (this.Width / 2) - 40, 80, 80);

This draws circle in form centre.

Good luck in experimenting and learning!