9

I have written a UserControl that behaves like a ContainerControl, but is totally painted by WindowsForms (I inherit from UserControl)

I would like to avoid painting the control while I'm filling it, so I would need to write something similar to BeginUpdate() - EndUpdate().

This is easy to do when the control is user-painted, but in this case I'm not sure about how to proceed.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Daniel Peñalba
  • 30,507
  • 32
  • 137
  • 219

2 Answers2

12

You could make use of Suspend/Resume layout. e.g.

private void BeginUpdate()
{
  this.SuspendLayout();
  // Do paint events
  EndUpdate();
}

private void EndUpdate()
{
   this.ResumeLayout();
   // Raise an event if needed.
}

If you're interested in suspending the painting of a control and it's children, check out this SO question: Suspend Control and Children Painting

Community
  • 1
  • 1
George Johnston
  • 31,652
  • 27
  • 127
  • 172
  • 5
    As far as I understand, SuspendLayout does not necessarily stop the control from painting. It is mostly useful on containers such as the FlowLayoutPanel, which performs layout operations on its children. It would be used to avoid performing layout operations each time you add a control to the panel, say in a loop. I might be wrong, but I would love some more info if you have any. – Craigt Feb 14 '11 at 16:04
1

You could override the OnPaint method and only pass control back to the base.OnPaint() when satisfying a certain condition.

    private bool _doPaint = true;
    protected override void OnPaint(PaintEventArgs e)
    {
        if(_doPaint)
            base.OnPaint(e);
    }

Then handle setting the _doPaint variable to the appropriate value with Public methods or a property.

You might have to override OnPaintBackground() in a similar way, depending on your needs.

Craigt
  • 3,418
  • 6
  • 40
  • 56
  • 1
    I chose this method. Since my control is meant for other devs to use I also added a safety timer that re-enables `_doPaint` 1500ms later in case their code doesn't turn it back on correctly. – QuickDanger Sep 08 '17 at 20:45