I've made a basic functionality calculator using VS WinForms App (.net core 6.0) and I want to fix design issues.
The problem is that when an input is ~20 symbols long you can't see the whole expression. That's why I want the program to rezise the font size automatically.
Source code: https://github.com/yanu1ya/Calculator
At first I wanted to check the textBox length everytime TextChanged event of textBox is triggered and set some font size according to that value. Unfortunately, different symbols have different width ('9' is a bit wider than ' ', at least in my app) so setting certain font size for certain length of the textBox doesn't work well for me. The next screenshot shows that different expressions are 18 and 22 symbols long but the width is the same: https://imgur.com/a/tCLNzcr
CodePudding user response:
When the contents of the Textbox changes, you can use the MeasureText to see if the text will be wider than the client area of the box. If so, you can drop the font size down. Note that below is just a quick and dirty example, you would want to cap the minimum font size at some sane value.
private void textBox1_TextChanged(object sender, EventArgs e)
{
using(var graphics = textBox1.CreateGraphics())
{
var size = TextRenderer.MeasureText(graphics, textBox1.Text, textBox1.Font);
if(size.Width > textBox1.ClientRectangle.Width)
{
textBox1.Font = new Font(textBox1.Font.FontFamily, textBox1.Font.Size-1);
}
}
}