Question

I have a form with a textbox and 2 buttons. I need the 2 buttons to increase and decrease the text size when clicked. Is there a way I can do this?

Was it helpful?

Solution

Assuming you are using winforms
Create two buttons named: btnFontSizeUp and btnFontSizeDown use the following code on click events:

btnFontSizeUp on click:

float currentSize;

currentSize = textboxName.Font.Size;
currentSize += 2.0F;
textboxName.Font = new Font(textboxName.Font.Name, currentSize, 
textboxName.Font.Style, textboxName.Font.Unit);

btnFontSizeDown on click:

float currentSize;

currentSize = textboxName.Font.Size;
currentSize -= 2.0F;
textboxName.Font = new Font(textboxName.Font.Name, currentSize, 
textboxName.Font.Style, textboxName.Font.Unit);

OTHER TIPS

In the event handler for the buttons call a resize method but you need to be sure it's not going to clash with the rest of the forms controls

private void ResizeTextbox(TextBox tb, ResizeDirection direction)
{
    switch (direction) 
    {
         case ResizeDirection.Up:
              tb.Height += 2;
              tb.Width += 2;
              tb.Font = new Font(tb.Font, tb.Font.Size + 1);
              break;
         case ResizeDirection.Down:
              tb.Height -= 2;
              tb.Width -= 2;
              tb.Font = new Font(tb.Font, tb.Font.Size - 1);
              break;
    }
}


enum ResizeDirection { Up, Down }
private void OnButtonClicked(object sender, EventArgs e)
{
   float f; 
   if(float.TryParse((sender as Button).CommandArgument, out f))
   {
       textBox.Font = new Font(textBox.Font.FontFamily, textBox.Font.Size + f);
   }
}

Make sure you give the relevant buttons a command argument of the amount you'd like to increment/decrement the font size by, and then wire up the event handler to both buttons.

According to MSDN TextBox, textbox has a property named font.

So you can do something like:

textbox.Font = new Font("Arial", 24,FontStyle.Bold);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top