-1

I get a JIT compiling error running this code

void draw(PaintEventArgs e)
{
     Graphics gr =this.CreateGraphics();
     Pen pen = new Pen(Color.Black, 5);
     int x = 50;
     int y = 50;
     int width = 100;
     int height = 100;
     gr.DrawEllipse(pen, x, y, width, height);
     gr.Dispose();
     SolidBrush brush = new SolidBrush(Color.White);
     gr.FillEllipse(brush, x,y,width,height);
 }

Error says: System Argument Exception: Invalid argument in FillEllipse(Brush, int32 x,int32 y,int32 width,int 32 height);

TaW
  • 53,122
  • 8
  • 69
  • 111
Alexandr Sargsyan
  • 656
  • 1
  • 6
  • 21
  • 1
    You do realize you are actually disposing the `Graphics` object and then attempting to use it again, do you? – Matias Cicero Apr 28 '15 at 14:06
  • ah sorry , I mention it after posting sorry, but now i have another question, how to make form size static in different monitors? by different dimensions? sorry and thank you – Alexandr Sargsyan Apr 28 '15 at 14:20
  • It is almost always a mistake to use `CreateGraphics`. Your `draw` method has a `PaintEventArgs` passed into it which I assume you get from a `Paint` event of some sort. You should use the Graphics instance that comes from that: `Graphics gr = e.Graphics`. And don't Dispose it either. – Chris Dunaway Apr 28 '15 at 15:40

1 Answers1

0

Since you are passing in the PaintEventArgs e you can and should use its e.Graphics!

And since you didn't create it, don't dispose of it!

But those Pens and Brushes you create you should disposed of or better yet, create them inside a using clause! For the SolidBrush we can use the standard Brush, which we can't change and must not dispose of either!

To be sure the Fill won't overwrite the Draw I have switched the order.

So, try this:

void draw(PaintEventArgs e)
{
     Graphics gr = e.Graphics;
     int x = 50;
     int y = 50;
     int width = 100;
     int height = 100;
     gr.FillEllipse(Brushes.White, x, y, width, height);
     using (Pen pen = new Pen(Color.Black, 5) )
        gr.DrawEllipse(pen, x, y, width, height);
 }
TaW
  • 53,122
  • 8
  • 69
  • 111