Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winforms Drawing - Parameter is not valid on system resume

I have an odd problem when my app is running and the system resumes from hibernation (in Windows 7).

I am calling the Graphics.DrawString method and this works fine most of the time. Except when the program is running and I hibernate the system. Then when I resume, the DrawString method throws an ArgumentException (Parameter is not valid) and gives me a red cross where my drawing should be.

What is going wrong here? Catching the exception avoids the red cross but when we get into this state there is no way back and the exception will keep being thrown until the program is restarted.

Thanks for any help, Alan

Edit: Here is the code that is failing:

protected override void OnPaint(PaintEventArgs e)
{
    // Drawing logic succeeds until this point

    e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), new PointF(x, y));
}

This is actually a subclass of ToolStripLabel.

like image 895
Alan Spark Avatar asked Nov 05 '22 19:11

Alan Spark


1 Answers

Many system resources become invalid after a sleep or hibernation. So your Font is probably invalid as that is a common cause of such issues. Also I note that you are not calling Dispose on the SolidBrush which you should do that to prevent resource leeks. Like this...

using(SolidBrush drawBrush = new SolidBrush(ForeColor))
    e.Graphics.DrawString(Text, Font, drawBrush, new PointF(x, y));
like image 53
Phil Wright Avatar answered Nov 15 '22 09:11

Phil Wright