Alex
Alex

Reputation: 3405

How to know if a textbox has wrapped lines?

I'm trying to change the font of a textbox when it is resized, in order to show the fittest font size, but mantaining the original text's line count. But I haven't achieved to know if lines is wrapped, to decrease the font size.

Could you give me an idea of how doing it?

Upvotes: 0

Views: 796

Answers (3)

Konrad Morawski
Konrad Morawski

Reputation: 8404

It can't be accomplished just by referring to the component's methods or properties.

You need to use EM_GETLINECOUNT message

Sample code (converted from original code sample in Visual Basic to C#):

using System.Runtime.InteropServices;

public class Form1
{    
    private const int EM_GETLINECOUNT = 0xba;
    [DllImport("user32", EntryPoint = "SendMessageA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
    private static extern int SendMessage(int hwnd, int wMsg, int wParam, int lParam);

    private void TextBox1_TextChanged(System.Object sender, System.EventArgs e)
    {
        var numberOfLines = SendMessage(textBox1.Handle.ToInt32(), EM_GETLINECOUNT, 0, 0);
    }
}

I have tested it and it works.

Upvotes: 3

Jen Grant
Jen Grant

Reputation: 2074

The System.Drawing.Graphics object has a Measure String function if you want a precise look at string lengths.

     System.Drawing.SizeF  len2 = graphic.MeasureString(*text*, *font*);

It doesn't take into account leading spaces, so for my measurements I used something like this to replace spaces with 'X' which was generally close in size.

     if (ibText.Content.Length > 0 && ibText.Content[0] == ' ')
           len2 = graphic.MeasureString(ibText.Content.Replace(' ', 'X'), ibText.Font);

Upvotes: 2

GameAlchemist
GameAlchemist

Reputation: 19294

maybe you could wrap your textbox inside a ViewBox instead : it will do the job of resizing for you.

Upvotes: 0

Related Questions