Custom controls: Fixing region not redrawn issue when window is moved or overlapped

Sometimes when we create a custom control by overriding its OnPaint method we might see the control not refreshed or redrawn when the parent window is moved to some other places which caused our custom  control to be invisible. This may be also seen when another window is placed/ moved to the top of our custom control which makes it invisible to the user at that moment. In this case when we move the top window, all other controls in our parent window except our custom control will get refreshed.

One major issue in the code will be the size of the rectangle we are painting. That is, in the OnPaint method to fill the region we might be using ClipBounds. for example  ( pe.Graphics.ClipBounds ). Instead of using ClipBounds use ClientRectangle property to fill the rectangle.


Example:
 protected override void OnPaint(PaintEventArgs pe)
{
        pe.Graphics.FillRectangle(Brushes.Blue, ClientRectangle);
        base.OnPaint(pe);
}

Comments