Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to implement auto resizable text that fits a visible part of a TextBox?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading