簡體   English   中英

單擊按鈕后,保持 TextBox 中的選定文本仍處於選中狀態或焦點

[英]Remains the selected text in a TextBox still selected or focused after clicking a button

我的 winform 項目中有 2 個按鈕。 如果用戶單擊按鈕,我想在 TextBox 中的選定文本周圍添加<b></b><i></i> 我希望單擊每個按鈕后選定的文本仍然保持焦點。 單擊按鈕后使用以下代碼,焦點選定的文本消失。 我該如何解決這個問題?

private void btnBold_Click(object sender, EventArgs e)
   {
       string selectedTxt = TextBox1.SelectedText;
       TextBox1.SelectedText = "<b>" + selectedTxt + "</b>";
   }

private void btnItalic_Click(object sender, EventArgs e)
   {
        string selectedTxt = TextBox1.SelectedText;
        TextBox1.SelectedText = "<i>" + selectedTxt + "</i>";
   }

您可以通過SelectionStart屬性獲取 slectedtext 索引。 然后將SelectionLength和調用方法ScrollToCaret設置為“聚焦選定文本”。

private void button1_Click(object sender, EventArgs e)
{
    int index = textBox1.SelectionStart;
    int selectlength = textBox1.SelectedText.Length;
    textBox1.SelectedText = "<b>" + textBox1.SelectedText + "</b>";
    textBox1.Focus();
    textBox1.SelectionStart = index; // set the start position
    textBox1.SelectionLength = selectlength  + 7; // set length
    textBox1.ScrollToCaret();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM