简体   繁体   中英

C# WinForm Auto resize textbox

I am using WinForms and I am trying to pass text from one textbox1 to another textbox2. The point is, that textbox2 must auto resize based on content of textbox1. I managed to get it done with one exception. When you create new lines in textbox1, it does the thing. But when you are writing with spaces but not creating new line it doesn't resize properly my textbox2. It resizing it but not fully by some reason.

This is what I have tried to do.

    private void PassTextFunction()
    {
        const int X_Main = 95;
        const int Y_Main = 60;
        Size size = TextRenderer.MeasureText(TextBox1.Text, TextBox1.Font);
        TextBox2.Text.ClientSize = new Size(size.Width + X_Main, size.Height + Y_Main);
        int nInterval = 10;
        string res = String.Concat(TextBox2.Text.Select((c, i) => i > 0 && (i % nInterval) == 0 ? c.ToString() + Environment.NewLine : c.ToString()));
        TextBox2.Text = TextBox1.Text.ToString();
    }

So when I Making lines everything resizing perfectly fine. Here is example: https://imgur.com/zxd5aCd

But when I write without next line, just simply typing, the rest of the text are hidden below and textbox2 doesn't resize completely by some reason. Here is example: https://imgur.com/ftbiP55

Does anybody can help me with fixed code for me please?

Have a look at the overload taking string , Font , Size and TextFormatFlags .

For the parameter of the type Size use the ClientSize of the textbox (or a new Size with the width of the textbox) (and possibly add your X_Main and Y_Main -- I'm not sure what they're for) and at least include TextFormatFlags.WordBreak for the TextFormatFlags (and have a look at the other ones, if they can be of use for you too).

...
Size size = TextRenderer.MeasureText(TextBox1.Text, TextBox2.Font, TextBox2.ClientSize, TextFormatFlags.WordBreak);
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM