Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why OnPaint is not called anymore if it fails to load a picture once?

Tags:

c#

onpaint

I found something that I do not really get:

protected override void OnPaint(PaintEventArgs e)
{
    DrawChar(e.Graphics);
    base.OnPaint(e);
}

void DrawChar(Graphics g)
{
    if (body != null)
    {
        g.DrawImage(body, X, Y);
    }
}

Suppose the "body" is empty - If I remove the condition in the DrawChar, the program never draws anything and I found out that the onPaint is not even raised anymore (e.g. when resizing or minimazing and restoring the window).

EDIT: The point is - if the DrawImage fails (which you do not know from the debugger, it simply does not draw the image e.g. when the Image is null), the OnPaint event in the application ceases to be raised.

like image 735
John V Avatar asked Aug 14 '18 15:08

John V


1 Answers

As if the failed DrawImage caused some error state

Yes, that is exactly what it does. An exception in a Paint event handler is extremely awkward, it makes continuing to debug a program hard to do. If nothing were done, such an exception would be raised over and over again when you continue debugging, making too difficult to diagnose another exception in the program. This concern is dated, goes back to the Win2000/XP days when Aero did not yet exist.

The method that does this is the one that calls OnPaint(), it is an internal method named Control.PaintWithErrorHandling(). Have a look-see, the error state you correctly postulated is named STATE_EXCEPTIONWHILEPAINTING. When it is set once then it always falls back to PaintException(), it draws the Red Cross of Failure. Thus avoiding the risk of raising the exception again. I'll copy/paste the comment:

    // Exceptions during painting are nasty, because paint events happen so often.
    // So if user painting code ----s up, we make sure never to call it again,
    // so as not to spam the end-user with exception dialogs.

The dashes used to spell the f-word, sanitizing the source code before open-sourcing it took quite a while and caused a fair amount of damage when they tried to automate it :)

like image 159
Hans Passant Avatar answered Sep 21 '22 01:09

Hans Passant