Share via


HOW TO:在 Windows Form TextBox 控制項中選取文字

更新:2007 年 11 月

你可以程式設計的方式選取 Windows Form TextBox 控制項中的文字。例如,如果你建立搜尋特定字串文字的功能,則可選取此文字以視覺地警示找到字串位置的讀取器 (Reader)。

若要以程式設計的方式選取文字

  1. SelectionStart 屬性設定為要選取的文字的字首。

    SelectionStart 屬性是用來指示文字字串內插入點的數字,其中 0 表示最左的位置。如果 SelectionStart 屬性設定成大於或等於文字方塊中的字元數,則會將插入點放置在最後一個字元之後。

  2. SelectionLength 屬性設定為要選取的文字長度。

    SelectionLength 屬性是設定插入點寬度的數值。將 SelectionLength 設定為大於 0 的數字時,則會從目前的插入點開始選取相同的字元數。

  3. (選擇性) 經由 SelectedText 屬性存取選取的文字。

    以下的程式碼會在發生控制項的 Enter 事件時,選取文字方塊的內容。TextBox1_Enter 事件處理常式必須繫結至此控制項;如需相關資訊,請參閱 HOW TO:建立 Windows Form 的執行階段事件處理常式

    Private Sub TextBox1_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Enter
       TextBox1.SelectionStart = 0
       TextBox1.SelectionLength = TextBox1.Text.Length
    End Sub
    
    private void textBox1_Enter(object sender, System.EventArgs e){
       textBox1.SelectionStart = 0;
       textBox1.SelectionLength = textBox1.Text.Length;
    }
    
    private void textBox1_Enter(Object sender, System.EventArgs e) 
    {
       textBox1.set_SelectionStart(0);
       textBox1.set_SelectionLength(textBox1.get_Text().get_Length());
    }
    
    private:
       void textBox1_Enter(System::Object ^ sender,
          System::EventArgs ^ e)
       {
          textBox1->SelectionStart = 0;
          textBox1->SelectionLength = textBox1->Text->Length;
       }
    

請參閱

工作

HOW TO:控制 Windows Form TextBox 控制項的插入點

HOW TO:使用 Windows Form TextBox 控制項建立密碼文字方塊

HOW TO:建立唯讀文字方塊 (Windows Form)

HOW TO:將引號放入字串中 (Windows Form)

HOW TO:檢視 Windows Form TextBox 控制項中的多行

參考

TextBox 控制項概觀 (Windows Form)

TextBox

其他資源

TextBox 控制項 (Windows Form)