您可以在 Windows Forms TextBox 控制項中以程式設計的方式選取文字。 例如,如果您建立了搜尋特定字串文字的函式,您可以選取該文字,以視覺化方式提醒讀者已找到的字串所在位置。
以程式設計的方式選取文字
將 SelectionStart 屬性設定為您想要選取之文字的開頭。
SelectionStart 屬性是一個數字,用來表示文字字串中的插入點,0 是最左邊的位置。 如果 SelectionStart 屬性的設定值等於或大於文字輸入框中的字元數,則插入點會放在最後一個字元之後。
將 SelectionLength 屬性設定為您想要選取之文字的長度。
SelectionLength 屬性是設定插入點寬度的數值。 將 SelectionLength 設定為大於 0 的數字,會促使從目前的插入點開始選取該數目的字元數。
(選擇性) 透過 SelectedText 屬性存取已選取的文字。
下列程式碼會在控制項的 Enter 事件發生時,選取文字輸入框的內容。 本範例會檢查文字輸入框是否具有非
null
或空字串之 Text 屬性的值。 當文字輸入框得到焦點時,會選取目前在文字輸入框中的文字。TextBox1_Enter
事件處理常式必須繫結至控制項;如需詳細資訊,請參閱操作說明:在執行階段建立 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; } }