views:

225

answers:

2

I've got a simple application that shows pictures dragged onto it. I'd like the application to resize itself according to the picture it displays. The code below does just that:

// Load the picture
Bitmap picture = new Bitmap(s);

// Calculate the size of the main form
this.Size = new Size(picture.Width + 
                       (this.pictureBox.Padding.All + 
                        this.pictureBox.Margin.All + 
                        this.tableLayoutPanel.Padding.All + 
                        this.tableLayoutPanel.Margin.All) * 2, 
                     picture.Height + 
                       (int)this.tableLayoutPanel.RowStyles[1].Height + 
                       (this.pictureBox.Padding.All + 
                        this.pictureBox.Margin.All + 
                        this.tableLayoutPanel.Padding.All + 
                        this.tableLayoutPanel.Margin.All) * 2);
 // Display the file.
 this.pictureBox.Image = picture;

It think it's fairly obvious where I'd like some help improving this. As the forms get more complicated, so would the calculation of the appropriate size. Suggestions?

+2  A: 

You could compute the difference in size between the old picture and the new picture, and then just adjust the size of the form by that amount... as long as all the other stuff on the form stays the same size.

Eric Rosenberger
+3  A: 

You can take a look at the Forms properties:

  • Form.AutoSize
  • Form.AutoSizeMode

Those, coupled with setting the PictureBox's AutoSizeMode should give you the effect you're looking for (without having to write any code).

TheSoftwareJedi
Wasn't aware of the AutoSize stuff... certainly that seems like the best way to go here.
Eric Rosenberger