title: WinForms Button: Autosize Maximumsize
body: <p>I want to add Buttons to a FlowLayoutPanel. The Buttons might contain longer texts with spaces between the words. The Buttons are Autosize=true and AutoSizeMode = AutoSizeMode.GrowAndShrink. Further more I set the MaximumSize property to (maxwidth,0). maxwidth is the width of the panel. So the button does not grow too wide.</p>
  
  <p>What I see is, that the widht of the Button is limited by the MaximumSize property, but when text wrapping occurs, the Button's height doesn't autosize to the height of the wrapped text. Is there a solution to that problem?</p>
  
  <hr>
  
  <p>I also tried this manually sizing the button like this:</p>
  
  <pre><code>using (Graphics cg = this.CreateGraphics()) {
  SizeF size = cg.MeasureString(button.Text, button.Font, 200);
    button.Width = (int)size.Width+20;
    button.Height = (int)size.Height+20;
    button.Text = someLongTextWithSpaces;
  }
  </code></pre>
  
  <p>But please note that I added 20 to the calculated size. It's working, but is there a proper way to determin this additional size? Maybe 2x Padding + ?????</p>
  
  <hr>
  
  <p>A few hours later...</p>
  
  <p>I came to this version which seems to work quite fine.</p>
  
  <pre><code>using (Graphics cg = this.CreateGraphics()) {
    var fmt = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak;
    var prop = new Size(tableLayoutPanel1.Width - 20, 0);
    var size = TextRenderer.MeasureText(button.Text, button.Font, prop, fmt);
  
    int border = button.Height - button.Font.Height;
    button.Width = (int)size.Width + border;
    button.Height = (int)size.Height + border;
    button.Text = someLongTextWithSpaces;
  }
  </code></pre>
  
  <p>It seems that the initial button height is borders + the height the font. So I calculated the border subtracting button.Height-button.font.Height.</p>
  
  <p>According to Hans, I now use the TextRenderer.MeasureText. I tested it without enabling VisualStyles and it worked fine. Any comments on that?</p>