Search code examples
c#winformspaintgroupbox

Using WinForm Paint event inside groupbox


I am tryign to port over this C++ MFC application into a C# WinForm. It is a work in progress. Basically, I want to do some drawing into the groupbox area:

Dialog design

I added a Paint handler to the Form to do my work:

private void FullColourPaletteForm_Paint(object sender, PaintEventArgs e)
{
    // Do painting with e.Graphics
}

I was surprised to see that it did not show my rendering. But, then I realised that in a Winform it is not called a groupbox but a container. So, I set the container to be invisible and understandably my rendering (albeit not quite right) was now visble:

Dialog results

How am I supposed to do my painting within the area of the container?

Why is this then? All I did was add:

private void groupBox1_Paint(object sender, PaintEventArgs e)
{
    base.OnPaint(e);
}

Now my forms painting is visible.


Solution

  • Each window (control, form etc.) has its own painting, and children are normally clipped (excluded) from that painting.

    If you want to draw inside the GroupBox (or any control), you should handle that in the corresponding control (GroupBox in your case) Paint event, not the form one.

    private void groupBox_Paint(object sender, PaintEventArgs e)
    {
        var area = groupBox.DisplayRectangle;
        // Draw inside the area
        e.Graphics.FillRectangle(Brushes.Green, area);
    }