Hi All,

I am fairly new to C# (From a VB.NET background). I have to edit some code left over from a previous person and I am running into a COMException error freeing memory. I have included the the complete function below and a screenshot of the error. Any help would be appreciated.

I have attached a screen shot of the error and the code is below.
Name:  06-01-2014 13-01-09.pngViews: 4Size:  57.2 KB


C#
public static Size CalculateTextExtent(string text, Font font, int maximumWidth, Graphics graphics, out int maximumCharactersThatFit, out int[] stringWidths)        {   
          maximumCharactersThatFit = 0;             
          stringWidths = new int[0];               

        if ((text == null) || (text.Length == 0)) return Size.Empty;               

        IntPtr tmp_oHdc = graphics.GetHdc();             
        IntPtr tmp_oFont = font.ToHfont();             
        IntPtr tmp_oPrevSelectedFont = NativeMethods.SelectObject(tmp_oHdc, tmp_oFont);
        
        NativeMethods.SIZE tmp_oSIZE = new NativeMethods.SIZE(0, 0);             
        IntPtr tmp_oStringWidthsArray = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * text.Length);             
        Int16 tmp_iMaxCharsTatFit = 0;             
        try             
        {                 
                NativeMethods.GetTextExtentExPoint(
                     tmp_oHdc,                     
                     text,                     
                     text.Length,                     
                     maximumWidth,                     
                     ref tmp_iMaxCharsTatFit,                     
                     tmp_oStringWidthsArray,                     
                     ref tmp_oSIZE);             
        }            
        finally             
        {                 
                NativeMethods.SelectObject(tmp_oHdc, tmp_oPrevSelectedFont);
                NativeMethods.DeleteObject(tmp_oFont);
                graphics.ReleaseHdc(tmp_oHdc);
        }               

        maximumCharactersThatFit = tmp_iMaxCharsTatFit;
        Size tmp_oResultSize = new Size(tmp_oSIZE.cx, tmp_oSIZE.cy);
        stringWidths = new int[maximumCharactersThatFit];
        Marshal.Copy(tmp_oStringWidthsArray, stringWidths, 0, stringWidths.Length);
        Marshal.FreeHGlobal(tmp_oStringWidthsArray);

        return tmp_oResultSize;   
      }