0

I use multiple panels and draw graphics on them.

Sometimes I need to add some changes to the graphics.

When I clear the panel and redraw everything inside - it works, but causes a flickering effect because all elements actually disappear and are created again.

Here is an example:

private void drawStatus() {
    Panel Panel1 = new Panel();
    Panel1.Width = 100;
    Panel1.Height = 100;
    Panel1.Location = new System.Drawing.Point(0, 0);
    Panel1.Visible = true;
    Panel1.Paint += new PaintEventHandler(Panel1Paint);
    panelDashboard.Controls.Add(Panel1);
}

private void Panel1Paint(object sender, PaintEventArgs e) {
    var g = e.Graphics;
    Pen PenGray = new Pen(Color.Gray, 1F);
    g.DrawRectangle(PenGray, SharedData.X, SharedData.Y, SharedData.W, SharedData.H);
    PenGray.Dispose();
    g.Dispose();
}

My thoughts are that I should fire PaintEventHandler again.

Panel1.Refresh() works for me, handler fires again, but it clears all panel content.

The question is, is it possible to fire the PaintEventHandler again without clearing the existing contents of the panel?

Or maybe there is another way to draw on the panel again.

burnsi
  • 6,194
  • 13
  • 17
  • 27
Paul WWJD
  • 133
  • 1
  • 1
  • 11
  • 1
    No, it's not possible. If you want to use a Panel as canvas, you have to double-buffer it (requires a Custom Control or Reflection), keeping in mind that a Panel is kind of *special* in this context. You'd get better results using a PictureBox or a Custom Control derived from Control -- Use `Invalidate()` instead of `Refresh()` -- Remove `g.Dispose();` – Jimi Feb 03 '23 at 19:35
  • 1
    Don't do this `g.Dispose();`. You don't create the `e.Graphics;` object then you're not responsible for disposing it. The `Panel` is not _DoubleBuffered_ by design as the `PictureBox` and you need to enable that yourself. Just use a `PictureBox` instead to fix the flickering problem. See also [this](https://stackoverflow.com/a/53708936/14171304) for example if you want to draw list of shapes. – dr.null Feb 03 '23 at 19:36
  • 1
    Thanks, @dr.null. `PictureBox` instead of `Panel` works like a charm. – Paul WWJD Feb 03 '23 at 20:01
  • 1
    And with `Invalidate()` mentioned by @Jimi - there is no flickering at all. Thanks a lot! – Paul WWJD Feb 03 '23 at 20:02

0 Answers0