c# - How to prevent ExternalException which occurs on graphics object -


i'm working on project control updates , new image drawn on panel after every 10 seconds. following code clears panel first. draws border it.

private void drawrectangle(color color) {    using (var graphics = creategraphics())    using (var pen = new pen(color))    {       graphics.clear(color.black);    //external exception thrown here.       graphics.drawrectangle(pen, 0, 0, size.width - 1, size.height - 1);    } } 

normally works fine if lock windows(press win + l) after 10 seconds when graphics.clear(color.black) statement executed, application crashes.

according msdn page: the clear method clears state of graphics object , should not called when graphics object cannot updated. example, if clear method called on secure desktop in terminal server session, externalexception may occur, leaving graphics object in inconsistent state.

what should prevent crash? should check if windows locked or not? , case crash occur?

update: same problem occurs when screen saver activated.

if call creategraphics() when windows locked or screensaver shown, graphics object returns in inconsistent state , can not used paint. if use such graphics object, throws externalexception.

best way rid of problem suggested user hans passant. instead of using creategraphics() method create graphics object, use panel's paint event. paint event handler contains eventargs contains graphics object. graphics object should used painting.

the reason works because, panel's paint event not called when windows locked or screensaver shown. no inconsistent graphics object used painting.


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -