The below code block which throws
System.Runtime.InteropServices.ExternalException: 'A generic error occurred in GDI+.
exception when the string passed to draw is too long.
public partial class Form1 : Form
{
string longString;
public Form1()
{
InitializeComponent();
for (int i = 0; i < 40000; i++)
longString += "s";
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.DrawString(longString, new Font("Segeo UI", 11, FontStyle.Regular), new SolidBrush(Color.Black), new RectangleF(0, 0, 100, 30),
new StringFormat()
{
LineAlignment = StringAlignment.Center,
Alignment = StringAlignment.Center,
Trimming= StringTrimming.None,
FormatFlags = StringFormatFlags.DirectionRightToLeft
});
}
}
How to resolve this exception when drawing long string with the specified format?
"Segeo UI"FontFamily. You're also leaking graphics objects all over the place. You may also want to change the string construction inlongString = new string('s', 40000);StringTrimming.None, which implies that your string is rendered completely, even though only the section defined by the constraint you've set will be visible. If you setStringTrimming.Character, only the section the fits the BlackBox is rendered. But, the whole string is measured anyway and if it exceeds the bounds of current DC, GDI+ will complain and you'll probably see the Red Cross in the background of your From.