views:

65

answers:

3

Hey all,

In the process of translating an application with C# + Winforms, I need to change a button's text depending on the language.

My problem is the following :

Let's say I want to translate a button from "Hi all!" to "Bonjour tout le monde" !

As you can guess, the button's size won't be the same if I enter english text or french one... My question is "simple", how can I manage to resize the button on the fly so the text fits its content in the button ?

So far I got something like that !

[Hi all!]

[Bonjour]

Thanks in advance for your help !

Andy

+2  A: 

You might try MeasureString:

http://msdn.microsoft.com/en-us/library/system.drawing.graphics.measurestring.aspx

Tim
+5  A: 

Resizing is easy. You can just set the button's width. The trick is making it big enough to fit your text.

   using(Graphics cg =  this.CreateGraphics())
   {
       SizeF size = cg.MeasureString("Please excuse my dear aunt sally",this.button1.Font);
       size.Width+= 3; //add some padding
       this.button1.Width = (int)size.Width;

       this.button1.Text = "Please excuse my dear aunt sally";
   }
Conrad Frix
Thank you very much !
Andy M
+1  A: 

There's absolutely no need to use the Graphics object as the other posters have said.

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.

That being said, you may need to make several layout adjustments to make this change fit into your UI. You can adjust the button's padding to add space around the text, and you may want to place your buttons in a TableLayout panel (or something) to stop them from overlapping when they resize.

ach
For the OP's need, this may be a much better solution because it sounds like they are dealing with a fairly straightforward secnario. However the statement "absolutely no need" is misleading. MeasureString is one of the best tools a programmer building custom forms and controls has available. It's also handy for web programmers (via an HTTP handler) to create precisely sized images based on variable text.
Tim
@Tim - I'm not saying anything negative about MeasureString, it has it's uses, but this is unequivocally not one of them. Riddling your code with unnecessary and arbitrary (width += 3) code is a bad practice.
ach