[VB.NET] TextBox 設定第幾行選取

  • 7821
  • 0

[VB.NET] TextBox 設定第幾行選取

 

TextBox 設定第幾行選取,使用以下 TextBox 的 Function 和 Property:

Function

Focus:設定控制項的輸入焦點。

http://msdn.microsoft.com/zh-tw/library/system.windows.forms.control.focus.aspx

GetFirstCharIndexFromLine:擷取指定行的第一個字元之索引。

http://msdn.microsoft.com/zh-tw/library/system.windows.forms.textboxbase.getfirstcharindexfromline(v=vs.110).aspx

Select:選取控制項內的文字。

http://msdn.microsoft.com/zh-tw/library/system.windows.forms.textboxbase.select.aspx

Property

Lines:取得或設定文字方塊控制項中的文字行數。

http://msdn.microsoft.com/zh-tw/library/system.windows.forms.textboxbase.lines.aspx

 

運用擴充方法,建立一個 TextBox 的擴充方法 SelectionLine,參考以下程式碼:

Imports System.Runtime.CompilerServices

Module TextBoxExtensions
     _
    Public Sub SelectionLine(ByVal textBox As TextBox, ByVal lineNumber As Integer)
        textBox.Focus()
        Dim beginIndex = textBox.GetFirstCharIndexFromLine(lineNumber)
        If beginIndex = -1 Then
            Return
        End If
        Dim linelength = textBox.Lines(lineNumber).Length
        textBox.Select(beginIndex, linelength)
    End Sub
End Module

 

如果要讓 TextBox 的第三行反白,使用方式如下,請注意行從 0 開始

TextBox1.SelectionLine(3)

 

執行結果

 

其他相關資訊

HOW TO:呼叫擴充方法 (Visual Basic)