I'm working on a project where control updates and new image is drawn on a panel after every 10 seconds. Following code clears that panel first. Then draws a border to it.
private void DrawRectangle(Color color)
using (var graphics = CreateGraphics())
using (var pen = new Pen(color))
graphics.Clear(Color.Black); //External exception is thrown here.
graphics.DrawRectangle(pen, 0, 0, Size.Width - 1, Size.Height - 1);
If you call CreateGraphics() when windows is locked or screensaver is shown, the graphics object it returns is in Inconsistent state and can not be used to paint. If we use such graphics object, it throws ExternalException.
Best way to get rid of this problem is suggested by user Hans Passant. Instead of using CreateGraphics() method to create graphics object, use panel's paint event. Paint event handler contains eventargs which contains graphics object. This graphics object should be used to do painting.
The reason this works because, panel's paint event does not get called when windows is locked or screensaver is shown. So no inconsistent graphics object is used for painting.