What happens after Form constructor?

  • Thread starter Thread starter Morgan Cheng
  • Start date Start date
M

Morgan Cheng

I am writing a very simple Win Form app.
One PictureBox (named ViewPicBox) in the main form (named ViewForm). In
the constructor of ViewForm, I set the Image property of ViewPicBox.

ViewForm()
{
InitializeComponent(); // auto generated by VS2005
ViewPocBox.Image = Image.FromFile(@"C:\abc.jpg");
}
After Ctrl+F5, it works fine and display the image.

Then I tried to use Graphics and modify the code to be:
ViewForm()
{
InitializeComponent(); // auto generated by VS2005
drawImage(@"C:\abc.jpg");
}

void drawImage(string fileName)
{
Image pic = Image.FromFile(fileName);
Graphics graph = ViewPicBox.CreateGraphics();
graph.DrawImage(pic, 0, 0, pic.Width, pic.Height);
graph.Dispose();
pic.Dispose();
}

It will not diplay the image after launched. I tried to call drawImage
in menu item event handler, it works fine. So, I suppose there is
something happened after ViewForm constructor that clear the content of
ViewPicBox.

Anyone knows what happens after the form constructor?
 
Morgan Cheng said:
It will not diplay the image after launched. I tried to call drawImage
in menu item event handler, it works fine. So, I suppose there is
something happened after ViewForm constructor that clear the content of
ViewPicBox.

Anyone knows what happens after the form constructor?

This is the #1 question in Bob Powell's faq (link below). Whatever is drawn
onto your form is not permanent and needs to be redrawn every time i new
part of your window is show. For example if the window is minimised then the
picture will need to be redrawn when it is next maximised, or if another
window covers part of it it will need to be redrawn. The solution is to draw
the image in the onpaint event.

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm
 
Thanks.

But, call CreateGraphics and then dispose it in each Paint event
repeatedly seems a little wasteful. Will it impact performance?
 
You don't need to call CreateGrapics there. OnPaint (or Paint event
handler) has a PaintEventArgs parameter. Check out
PaintEventArgs.Graphics.
 
Morgan Cheng said:
Thanks.

But, call CreateGraphics and then dispose it in each Paint event
repeatedly seems a little wasteful. Will it impact performance?

As morgan said you can just use e.Graphics in the paint event. Loading the
bitmap from file each time is more of a issue though. You should store the
bitmap somewhere and reuse it. This might seam wasteful but the bitmap has
to be stored somewhere, if you used a picturebox it would keep the bitmap in
memory.

Michael
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top