Jamie
Jamie

Reputation: 7411

Looking for a better way to change parent form's size

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?

Upvotes: 2

Views: 347

Answers (2)

TheSoftwareJedi
TheSoftwareJedi

Reputation: 35196

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).

Upvotes: 4

Eric Rosenberger
Eric Rosenberger

Reputation: 9117

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.

Upvotes: 3

Related Questions