如何从多行文本框中获取换行? [英] how to get wrapped lines from multiline textbox?
问题描述
在我的 windows.forms c# 应用程序中,我有一个 WordWrap = true 的多行文本框.将 Text 属性设置为长字符串后,我需要通过换行获取所有行.它与 Lines[] 属性不同,因为我的文本不包含换行符.我已经找到了使用图形 MeasureString 函数的解决方案,但考虑到文本框控件已经完成了包装,这似乎有点额外的工作 - 为什么我还要再次做同样的工作?有什么办法可以让文本框将文本换行吗?
In my windows.forms c# application, I have a multi-line textbox with WordWrap = true. After I set Text property to a long string, I need to get all lines produced by wrapping. It is not the same as Lines[] property, because my text does not include new line characters. I have found solutions using graphics MeasureString function but it seems a little bit extra work considering that the textbox control already did the wrapping - why should I do the same work again? Is there any way to get the lines into which the textbox wraps the text?
谢谢
推荐答案
您可以查看以下解决方案吗,
Can you check the below solution,
public Form1()
{
InitializeComponent();
textBox1.Text = "This is my text where I want to check how I can get wrapped content as seperate lines automatically !! This is my text which I want to check how I can get wrapped content as seperate lines automatically !!";
}
private void button1_Click(object sender, EventArgs e)
{
bool continueProcess = true;
int i = 1; //Zero Based So Start from 1
int j = 0;
List<string> lines = new List<string>();
while (continueProcess)
{
var index = textBox1.GetFirstCharIndexFromLine(i);
if (index != -1)
{
lines.Add(textBox1.Text.Substring(j, index - j));
j = index;
i++;
}
else
{
lines.Add(textBox1.Text.Substring(j, textBox1.Text.Length - j));
continueProcess = false;
}
}
foreach(var item in lines)
{
MessageBox.Show(item);
}
}
文本框中的行号从零开始.如果行号参数大于文本框中的最后一行,GetFirstCharIndexFromLine 返回 -1.
Line numbering in the text box starts at zero. If the lineNumber parameter is greater than the last line in the text box, GetFirstCharIndexFromLine returns -1.
GetFirstCharIndexFromLine 返回第一个字符的索引物理线.物理线是显示的线,而不是分配的线路.显示的行数可以大于由于自动换行而分配的行数.例如,如果您分配两个长行到 RichTextBox 控件并设置 Multiline 和 WordWrap为真,两条长指定行导致四个物理(或显示的行).
这篇关于如何从多行文本框中获取换行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!