tags:

views:

110

answers:

2

I wrote a simple C# program using some graphic functions as drawElipse and drawLine at System.Drawing.Graphics. It works perfectly on one computer, but at my laptop it gives overflow exception at the graphics functions. I need the program to work on the laptop for a presentation after five hours, please help me.

Here are the two functions I get the error in:

private void drawDot(int n)
{
    Graphics gfx = CreateGraphics();
    int mapx = (int)verts[n].mapx;
    int mapy = (int)verts[n].mapy;
    Pen myPen = new Pen(Color.DarkOliveGreen, 5);
    if (mapx > 2 && mapy > 2)
    {

        Rectangle rect = new Rectangle((int)mapy - 2, (int)mapx - 2, 10, 10);
        gfx.DrawEllipse(myPen, rect);
    }

}

private void drawLine(int n, int k)
{
    int mapnx = (int)verts[n].mapx;
    int mapny = (int)verts[n].mapy;
    int mapkx = (int)verts[k].mapx;
    int mapky = (int)verts[k].mapy;
    Graphics gfx = CreateGraphics();
    Pen myPen = new Pen(Color.DarkOliveGreen, 3);
    gfx.DrawLine(myPen, mapny, mapnx, mapky, mapkx);
}
A: 

Perhaps this is related to one machine JITing to x64, while the other machine JITs to x86.

Brent Arias
If that's the problem, how to fix it?
Ivan Mechkov
+5  A: 

You need to explicitly dispose the Graphics object in the method you have called. You can do this in two different ways.

  1. Explicitly call gfx.Dispose() at the end of your methods.
  2. Wrap the code that accesses gfx in using, like this:

    using (Graphics gfx = CreateGraphics())
    {
        // call gfx methods liek DrawLine()
    }
    

You can read a bit more in the MSDN documentation for the CreateGraphics() method.

Franci Penov
Note that Pen is IDisposable as well.
TrueWill