删除光标所在的一行文本

Remove a line of text where the cursor is positioned

我下面的所有代码都删除了 TextBox 中的所有空行。
但是我希望在单击按钮时删除光标指向的线。

'First method
TextBox2.Lines = TextBox2.Lines.Where(Function(l) Not String.IsNullOrWhiteSpace(l)).ToArray()
Dim count = TextBox2.Lines.Length

'Second method
Dim tmp() As String = TextBox2.Text.Split(CChar(vbNewLine))
TextBox2.Clear()
For Each line As String In tmp
    If line.Length > 1 Then
        TextBox2.AppendText(line & vbNewLine)
    End If
Next

'Third method
Dim SearchIn = Me.TextBox2.Text
Dim sb As StringBuilder = New StringBuilder(SearchIn)
Me.TextBox2.Text = sb.Replace(vbCrLf + vbCrLf, vbCrLf).ToString

'Fourth method
TextBox2.Text = Regex.Replace(TextBox2.Text, "(?<Text>.*)(?:[\r\n]?(?:\r\n)?)", "${Text} ") + "/n"

TextBox2.Text = Replace(TextBox2.Text, vbCrLf & vbCrLf, vbCrLf)

要从 TextBoxBase 派生控件(TextBox、RichTextBox)中删除一行文本,您首先必须确定正确的行。

如果文本被换行,则不能使用 .Lines 属性,因为它会 return 相对于未换行文本的行号。

您可以通过GetLineFromCharIndex()获取当前换行。 Integer 参数是当前插入符位置,由 SelectionStart 属性.

引用

该行的第一个字符索引由GetFirstCharIndexFromLine()返回。

然后,找到当前行的长度,确定第一个换行符。添加换行符号的长度以将它们包含在计算的长度中。

注意 TextBox 控件使用 Environment.Newline 生成换行符 ("\r\n"),而 RichTextBox 控件仅使用换行符 ("\n").

这将删除插入符当前所在的任何行:
(如果你只想允许删除空行,请检查行长是否为< 3)。

Dim CurrentPosition As Integer = TextBox2.SelectionStart
Dim CurrentLine As Integer = TextBox2.GetLineFromCharIndex(CurrentPosition)
Dim LineFirstChar As Integer = TextBox2.GetFirstCharIndexFromLine(CurrentLine)
Dim LineLenght As Integer = TextBox2.Text.
                            IndexOf(Environment.NewLine, LineFirstChar) - LineFirstChar +
                            Environment.NewLine.Length
If LineLenght <= 0 Then Return

TextBox2.Select(LineFirstChar, LineLenght)
TextBox2.SelectedText = TextBox2.SelectedText.Remove(0)
TextBox2.SelectionLength = 0
TextBox2.SelectionStart = If(CurrentPosition < TextBox2.Text.Length, LineFirstChar, TextBox2.Text.Length)
TextBox2.Focus()

这将删除包含插入符号的整个段落:

Dim CurrentPosition As Integer = TextBox2.SelectionStart
Dim ParagraphFirstIndex As Integer = TextBox2.Text.
                                     LastIndexOf(Environment.NewLine, CurrentPosition) +
                                                 Environment.NewLine.Length
Dim LineFeedPosition As Integer = TextBox2.Text.IndexOf(Environment.NewLine, ParagraphFirstIndex)
LineFeedPosition = If(LineFeedPosition > -1, LineFeedPosition + Environment.NewLine.Length, TextBox2.Text.Length)

Dim LineLenght As Integer = LineFeedPosition - ParagraphFirstIndex
If LineLenght <= 0 Then Return

TextBox2.Select(ParagraphFirstIndex, LineLenght)
TextBox2.SelectedText = TextBox2.SelectedText.Remove(0)
TextBox2.SelectionLength = 0
TextBox2.SelectionStart = If((CurrentPosition < TextBox2.Text.Length), ParagraphFirstIndex, TextBox2.Text.Length)
TextBox2.Focus()