Search code examples
.netvstooutlook-addinsystem.drawing.graphics

VSTO Outlook Plugin: MeasureString calculates wrong width


I want to display a button with an internationalized label. In English the label perfectly fits the width of the button. In german it does not fit. To calculate dynamically the width I use [...]

using (Graphics cg = this.CreateGraphics())
            {
                SizeF size = cg.MeasureString(OutlookAddIn4.Resources.Resources.ShowLoginText, this.showLogFile.Font);
                this.showLogFile.Width = (int)size.Width+3;
            }

[...]

For the String in OutlookAddIn4.Resources.Resources.ShowLoginText="Logfile anzeigen". In calculates 125 pixels. I even added 3 pixels. Padding for the button is set to 0. Why does it calculate the wrong width? this.showLogFile.Font is set to the right Font (Microsoft Sans Serif, 12 pt) (checked this in the debugger).


Solution

  • There is no need to use the underlying Graphics object.

    If you set the button's AutoSize property to true, the AutoSizeMode to GrowAndShrink, and the AutoEllipsis to false, it will resize automatically to fit the text.

    But if you really need to use the Graphics objects:

       using(Graphics cg =  this.CreateGraphics())
       {
           SizeF size = cg.MeasureString("Your text goes here",this.button1.Font);
    
           this.button1.Padding = 3;
           this.button1.Width = (int)size.Width;
    
           this.button1.Text = "Your text goes here";
       }