Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does text drawn on a panel disappear?

Tags:

c#

winforms

I'm trying to draw a text on a panel(The panel has a background picture).

It works brilliant,but when I minimize and then maximize the application the text is gone.

My code:

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

How do I keep it static so it doesn't get lost?

like image 521
Ivan Prodanov Avatar asked Jun 03 '09 17:06

Ivan Prodanov


3 Answers

Inherit from Panel, add a property that represents the text you need to write, and override the 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));
    }
}

This way, each Panel will know what it needs to render, and will know how to paint itself.

like image 61
BFree Avatar answered Oct 23 '22 16:10

BFree


Just add a handler for the Paint event:

private void panel1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.DrawString("a", new Font("Tahoma", 5), Brushes.White, new PointF(1, 1));
}
like image 33
Jon B Avatar answered Oct 23 '22 16:10

Jon B


If you don't use a Paint event, you are just drawing on the screen where the control happens to be. The control is not aware of this, so it has no idea that you intended for the text to stay there...

If you put the value that you want drawn on the panel in it's Tag property, you can use the same paint event handler for all the panels.

Also, you need to dispose of the Font object properly, or you will be having a lot of them waiting to be finalized before they return their resources to the system.

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));
   }
}
like image 23
Guffa Avatar answered Oct 23 '22 18:10

Guffa