如何:在 Windows Form TextBox 控制項中選取文字

您可以在 Windows Forms TextBox 控制項中以程式設計方式選取文字。 例如,如果您建立搜尋特定字串文字的函式,您可以選取文字,以視覺化方式警示找到字串位置的讀取器。

以程式設計方式選取文字

  1. SelectionStart 屬性設定為您想要選取之文字的開頭。

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

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

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

  3. (選擇性)透過 屬性存取選取的 SelectedText 文字。

    下列程式碼會在控制項 Enter 的事件發生時選取文字方塊的內容。 本範例會檢查文字方塊是否有不是 null 或空字串之 屬性的值 Text 。 當文字方塊收到焦點時,會選取文字方塊中的目前文字。 TextBox1_Enter事件處理常式必須系結至 控制項;如需詳細資訊,請參閱 How to: Create Event Handlers at Run Time for Windows Forms

    若要測試此範例,請按 Tab 鍵,直到文字方塊有焦點為止。 如果您在文字方塊中按一下,則會取消選取文字。

    Private Sub TextBox1_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Enter  
       If (Not String.IsNullOrEmpty(TextBox1.Text)) Then  
          TextBox1.SelectionStart = 0  
          TextBox1.SelectionLength = TextBox1.Text.Length  
       End If  
    End Sub  
    
    private void textBox1_Enter(object sender, System.EventArgs e){  
       if (!String.IsNullOrEmpty(textBox1.Text))  
       {  
          textBox1.SelectionStart = 0;  
          textBox1.SelectionLength = textBox1.Text.Length;  
       }  
    }  
    
    private:  
       void textBox1_Enter(System::Object ^ sender,  
          System::EventArgs ^ e) {  
       if (!System::String::IsNullOrEmpty(textBox1->Text))  
       {  
          textBox1->SelectionStart = 0;  
          textBox1->SelectionLength = textBox1->Text->Length;  
       }  
    }  
    

另請參閱