c# - 如何从多行文本框中获取换行?

标签 c# textbox multiline word-wrap

在我的 windows.forms c# 应用程序中,我有一个 WordWrap = true 的多行文本框。在我将 Text 属性设置为一个长字符串后,我需要获取通过换行生成的所有行。它与 Lines[] 属性不同,因为我的文本不包含换行符。 我找到了使用图形 MeasureString 函数的解决方案,但考虑到文本框控件已经进行了包装,这似乎有点额外的工作——为什么我还要再做同样的工作? 有什么方法可以获取文本框将文本换行到的行吗?

谢谢

最佳答案

你能检查下面的解决方案吗,

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 Reference

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 returns the first character index of a physical line. The physical line is the displayed line, not the assigned line. The number of displayed lines can be greater than the number of assigned lines due to word wrap. For example, if you assign two long lines to a RichTextBox control and set Multiline and WordWrap to true, the two long assigned lines result in four physical (or displayed lines).

关于c# - 如何从多行文本框中获取换行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36801006/

相关文章:

c# - 无法使用适用于 .NET 的 AWS 开发工具包获取预签名对象 URL

c# - 使用 LINQ Min() 获取对象?

linux - 使用 printf 在 bash 中格式化多行命令输出

python - 将多行 make-line 变量赋值与 python 正则表达式相匹配

正则表达式,用于在Eclipse中匹配 "non-javadoc"注释

c# - AspNetCore项目仅在Linux容器上提供System.IO.FileNotFoundException

c# - DeleteOnSubmit 不存在?

c# - 在文本框中输入文本时按钮出现问题

c# - WPF 始终关注文本框

c# - 验证我的表单