在 TextBox 中单击鼠标后,如何在多行 TextBox 中插入换行符?

How do I insert a newline in a multiline TextBox after mouse click in the TextBox?

当用户点击多行文本框时。我的表单应用程序应该在当前单击行的末尾插入一个新行。

例如,这些是我的文本框中的行:

-Hallo
-Dear
-Kindly

如果用户点击第二行 (-Dear),我的文本框中的值应该是:

-Hallo
-Dear

-Kindly

我的一次(失败)尝试没有插入换行符:

int line = txtProjects.GetLineFromCharIndex(txtProjects.SelectionStart);
txtProjects.Lines[line] = txtProjects.Lines[line].Insert(txtProjects.Lines[line].Length, Environment.NewLine);

如果您想将某些内容附加到数组中,您必须重新创建它,因为数组的大小是固定的。你可以使用 LINQ:

int lineCount = txtProjects.GetLineFromCharIndex(txtProjects.SelectionStart) + 1; // zero based
string[] lines = txtProjects.Lines;
txtProjects.Lines = lines 
    .Take(lineCount)
    .Concat(new[] {"\n"})
    .Concat(lines.Skip(lineCount))
    .ToArray();

一种可能更具可读性的方法是使用 List<string>.Insert:

List<string> lines = txtProjects.Lines.ToList();
lines.Insert(lineCount, "");  //  null works also
txtProjects.Lines = lines.ToArray();

如果你想保留 "cursor"-位置,你可以使用 TextBox.Select:

private void txtProjects_Clicked(object sender, EventArgs e)
{
    int cursorPos = txtProjects.SelectionStart;
    int lineCount = txtProjects.GetLineFromCharIndex(cursorPos) + 1; // zero based
    List<string> lines = txtProjects.Lines.ToList();
    lines.Insert(lineCount, null);
    txtProjects.Lines = lines.ToArray();
    txtProjects.Select(cursorPos, 0);
}

试试这个:

var p = TextBox1.GetLineFromCharIndex[TextBox1.SelectionStart];
List<string> str = new List<string>();
str.AddRange(TextBox1.Lines);
str.Insert(p + 1, "");
TextBox1.Text = "";
foreach (void st_loopVariable in str) {
    st = st_loopVariable;
    TextBox1.Text += st + Constants.vbNewLine;
}

它正在处理 vb。我将其转换为 C#,因此可能存在一些语法错误。