Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Word wrap without cutting words

4.50/5 (2 votes)
4 Jun 2012CPOL 13.3K  
Wrap multi-line text without cutting words.

Here is the code to wrap multi-line text without cutting words:

C#
private void Form1_Load(object sender, EventArgs e)
{
    // String
    string sss = "Farshid Ariashokooh Arvin Rose Software Gorup. www.arvin-rose.com";
    // Return The String with Font And Size
    string Ret = lineStringAnalys(sss, 160, new Font("Arial", 10, FontStyle.Bold));
    MessageBox.Show(Ret);                        
    this.Close();

}
private string lineStringAnalys(string _str, int _size, Font _font)
{
   string NewStr =_str;
   // If do not need to Check 
    if (TextRenderer.MeasureText(_str, _font).Width +5 < (_size))
        return _str; // Retun 
    int p1 = 0, p2 = 0 ;
    for (int i = 0; i < _str.Length; i++) // Check char by char the string 
    {
        p2++;
        try
        {
            if (p1 + p2 > _str.Length)
                break;
            if (TextRenderer.MeasureText(_str.Substring(p1, p2), _font).Width + 5 >= (_size))
            {
                int aaa = TextRenderer.MeasureText(_str.Substring(p1, p2), _font).Width;
                string bbbb = _str.Substring(p1, p2);
                int y = i, count = 0;
                while (_str.Substring(y, 1) != " ") // look for the last word
                {
                    y--;
                    count++;
                    if (y == 0 || y <= p1) // if not found word
                    {
                        count = 0;
                        break;
                    }

                }
                p2 -= count;
                NewStr = NewStr.Insert(p1 + p2, "\n");
                p1 += p2 + 1;
                
                p2 = 0;
                i -= count;
            }
        }
        catch
        {
            MessageBox.Show(i.ToString());
        }


    }
    return NewStr;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)