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; }