Uthistran Selvaraj.
Uthistran Selvaraj.

Reputation: 558

Draw someshapes in Panel without using Panel1_Paint() event

I am drawing something, let us assume an image over the panel in Windows form. I can able to draw i I follow the below steps:

1) added panel to the Form 2) used the below code:

private void panel1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawImage(im, leftTop);
    }

Is this the only way to draw over the panel.

I have a plan to draw withoutusing this event I tried by the below code, results negative.

this.panel1.CreateGraphics().DrawImage(im, leftTop);

in both the case im is an Image.

.. can I able to draw. ?

Upvotes: 0

Views: 1688

Answers (1)

King King
King King

Reputation: 63317

Yes, you can draw it, however if the Paint event is raised, the default stuff will be re-drawn and all the thing you have drawn will be covered/erased/cleared.

So to draw your image, the best approach is to add drawing code in Paint event handler as the first code you posted does.

Otherwise, you have to draw your image periodically which is not efficient, because we just need to re-draw it when we need. The system provides the Paint event to notify when we need to repaint the control (beside the default drawing).

Here is the way in which you use a timer to draw your image periodically, but this is not recommended, just for demonstrative purpose:

 Timer t = new Timer();
 t.Interval = 10;
 Graphics g = null;
 panel1.HandleCreated += (s,e) => {
   g = panel1.CreateGraphics();
 };
 t.Tick += (s,e) => {
    if(g == null) return;
    g.DrawImage(im,leftPoint);
 };
 //
 t.Start();

In fact, the Paint event is raised when the WM_PAINT is sent to your Panel, you can catch this message to draw the image instead of draw it when Paint is raised.

public class MyPanel : Panel {
  Graphics g;
  public MyPanel(){
     HandleCreated += (s,e) => {
       g = panel1.CreateGraphics();
     };
  }
  protected override void WndProc(ref Message m){
     base.WndProc(ref m);
     if(m.Msg == 0xf&&g!=null)//WM_PAINT = 0xf
        g.DrawImage(im,leftTop);
  }
  //.... suppose somehow you pass im and leftTop in...
}

Upvotes: 1

Related Questions