TextBox Word-Wrapping 将字符串拆分为行 [英] TextBox Word-Wrapping splitting string to lines
问题描述
这是我第一次在这个惊人的服务上发布问题,因为今天它通过阅读它对我有很大帮助.
This is my first time posting question on this amazing service, since today it has helped me a lot by just reading it.
目前,我正在制作需要使用大量文本框的小型 C# 应用程序.在 TextBox 属性中,我检查了 MultiLine 和 Word-Wrap 功能.所以当用户输入文本时,它会在多行中正确显示.
Currently, I'm making small C# application where I need to use a lot of TextBoxes. In TextBox Properties I have checked MultiLine and Word-Wrap functions. So when user enters text, it is displayed correctly in multiple lines.
我的问题是我怎样才能得到那些显示在表单上的行,在字符串列表中,而不是一个大字符串.
My problem is how can I get those lines, which are displayed on form, in list of strings, instead of one big string.
我还没有区分天气 Word-Wrap Function 换行或在每行末尾添加\n\r".我试图从 TextBox.Lines 获取行,但它只有 TextBox.Lines[0],其中包含整个字符串形式 TextBox
I haven yet distinguished weather Word-Wrap Function makes new lines or adds "\n\r" at the end of every line. I tried to get lines from TextBox.Lines , but it has only TextBox.Lines[0], which contains the whole string form TextBox
我已经尝试了很多东西并研究了很多资源,但我仍然没有找到解决这个问题的正确方法.
I have already tried many things and researched many resources, but I still haven't found right solution for this problem.
推荐答案
这里有很多极端情况.您要使用的核心方法是 TextBox.GetFirstCharIndexFromLine()
,它允许您在 TextBox 应用 WordWrap 属性后迭代行.样板代码:
Lots of corner cases here. The core method you want use is TextBox.GetFirstCharIndexFromLine()
, that lets you iterate the lines after TextBox has applied the WordWrap property. Boilerplate code:
var lines = new List<string>();
for (int line = 0; ;line++) {
var start = textBox1.GetFirstCharIndexFromLine(line);
if (start < 0) break;
var end = textBox1.GetFirstCharIndexFromLine(line + 1);
if (end == -1 || start == end) end = textBox1.Text.Length;
lines.Add(textBox1.Text.Substring(start, end - start));
}
// Do something with lines
//...
请注意行中包含行结尾.
这篇关于TextBox Word-Wrapping 将字符串拆分为行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!