Search code examples
c#stringwinformslabelmessagebox

How to split a label into multiple lines if it's too wide


I want to make my own message box, here are it's constructors:

    public MBX(string message)
    {
        InitializeComponent();
    }

    public MBX(string message, string title)
    {
        InitializeComponent();
    }

    public MBX(string message, string title, string[] buttons)
    {
        InitializeComponent();
    }

I would like to make a void that will reformat the message to have a width less than 444. Here's an example to help you out: Let's say that the message was: "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc" and that this string had a width greater than 444 pixels, what the void is going to do, is to split it into multiple lines until the width is lower than 444 like so:

abcabcabcabcabcabcabcabcabcabcabc
abcabcabcabcabcabcabcabcabcabcabc
abcabcabcabc

(You can keep in mind how the original message box reacts to long strings)

Thank you in advance! VBTheory

EDIT: After searching for a couple of weeks, I was able to find an article that treats exactly this word wrap issue: http://www.codeproject.com/Articles/51488/Implementing-Word-Wrap-in-C#_rating


Solution

  • Get the length of the string, if it is greater than 444, use the substring function to parse the full string from 0 to 444, and from 444 to string.Length(). If the second substring is still greater than 444, lather rinse and repeat. Put the strings into a string array, and to display in the message box, loop through the array inserting a new line escape character after each string element.