Why does the text drawn on the panel disappear?

I am trying to draw text on a panel (the panel has a background image).

It works brilliantly, but when I minimize and then maximize the application, the text goes away.

My code is:

using (Graphics gfx = Panel1.CreateGraphics())
{
    gfx.DrawString("a", new Font("Tahoma", 5), Brushes.White, new PointF(1, 1));
}

How to maintain static so that it is not lost?

+5
source share
4 answers

If you are not using an event Paint, you simply draw on the screen where the control is located. The control does not know about this, so it does not suspect that you were intended to keep the text there ...

, Tag, .

, Font, , .

private void panel1_Paint(object sender, PaintEventArgs e) {
   Control c = sender as Control;
   using (Font f = new Font("Tahoma", 5)) {
      e.Graphics.DrawString(c.Tag.ToString(), f, Brushes.White, new PointF(1, 1));
   }
}
+2

Panel, , , , OnPaintMethod():

public class MyPanel : Panel
{
    public string TextToRender
    {
        get;
        set;
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        e.Graphics.DrawString(this.TextToRender, new Font("Tahoma", 5), Brushes.White, new PointF(1, 1));
    }
}

, , , , .

+9

Paint:

private void panel1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.DrawString("a", new Font("Tahoma", 5), Brushes.White, new PointF(1, 1));
}
+4

When you draw something, it remains only until the next form update.

When the form is updated, the Paint event is raised. Therefore, if you want your text to not disappear, you need to include code that draws it in the Paint event.

You can call the redraw using Control.Invalidate, but otherwise you cannot predict when they will occur.

0
source

All Articles