How to make wordwrap consider a whitespace in a st

2019-09-18 14:35发布

问题:

I want to create a multiline textbox control that will be used for an application as "Snap to grid" when all of the characters are Monospaced, and the fitting font size was found (for example - for a textbox with 6 columns, exactly 6 characters should be entered). - Of course with Word Wrap!

As for the above - it's OK. The correct way to calculate the font size was found.

The only issue is that I need to create an "Alt+Enter" option to represent "Enter".

For some reasons, I can't use \r\n and need that all of the remaining line space will be full of whitespaces. The thing is that wrap doesn't accept spaces in an amount which is larger than the textbox's width. For example:

If I write in a textbox with width=8cells, the following (or paste that string etc..):

"Hello World!" ("Hello+6Whitespaces+World!")

I would like to recieve: (_=whitespace)

First Line: Hello___

Second Line: ___World

Third Line: !

What really happens is:

First Line: Hello___

Second Line: World!

(No spaces at all in the beginning of the second line)

PS - On debug I can see that the spaces (all of them) are considered as a part of the string.

回答1:

Firstly, try Environment.NewLine instead of \r\n. That will ensure you get the correct line breaks on your target platform.

Secondly, Word Wrap is likely ignoring extra spaces, so you need to replace normal spaces with a unicode non-breaking space. The unicode character for that is \u00A0.

You need to replace all normal spaces with the unicode non-breaking space:

string spaceReplacer = "\u00A0";

And to use it, try this:

textBox1.Text = textBox1.Text.Replace(" ", spaceReplacer);

Or even this:

textBox1.Text = textBox1.Text.Replace(" ", "\u00A0");