2017-03-02 27 views
0

我正在處理VS2013中的VB.NET 4.5項目。更改RichTextBox中字符串的所有實例上的字體樣式

我在窗體上有一個richtextbox,當單擊一個按鈕時,我需要在richtextbox中找到的特定字符串的所有實例上切換BOLD設置。

我把一些基於this question的代碼放在一起。

Private Sub ToggleBold() 

    rtxtOutputText.SelectionStart = rtxtOutputText.Find("@#$%", RichTextBoxFinds.None) 

    rtxtOutputText.SelectionFont = New Font(rtxtOutputText.Font, FontStyle.Bold) 
End Sub 

但是,當單擊切換粗體按鈕時,它只會粗體顯示字符串「@#$%」的第一個實例。

如何將字符串的所有實例設置爲粗體?也可以將它們中的幾個串聯在一起(「@#$%@#$%@#$%」),因此每一個都需要加粗。

(我知道我提到切換大膽的,但後來我將建立肘環部分,現在我只是試圖讓所有的情況下工作的權利大膽...)

回答

3

剛添加一個循環,並使用RichTextBox.Find(String, Int32, RichTextBoxFinds) overload來指定從哪裏開始尋找。從當前索引+1查看,以便它不會再次返回相同的值。

您也應該以實際選擇字爲好,讓你確信大膽適用於當前實例,而不是周圍的文本。

Private Sub ToggleBold() 
    'Stop the control from redrawing itself while we process it. 
    rtxtOutputText.SuspendLayout() 

    Dim LookFor As String = "@#$%" 
    Dim PreviousPosition As Integer = rtxtOutputText.SelectionStart 
    Dim PreviousSelection As Integer = rtxtOutputText.SelectionLength 
    Dim SelectionIndex As Integer = -1 

    Using BoldFont As New Font(rtxtOutputText.Font, FontStyle.Bold) 
     While True 
      SelectionIndex = rtxtOutputText.Find(LookFor, SelectionIndex + 1, RichTextBoxFinds.None) 

      If SelectionIndex < 0 Then Exit While 'No more matches found. 

      rtxtOutputText.SelectionStart = SelectionIndex 
      rtxtOutputText.SelectionLength = LookFor.Length 

      rtxtOutputText.SelectionFont = BoldFont 
     End While 
    End Using 

    'Allow the control to redraw itself again. 
    rtxtOutputText.ResumeLayout() 

    'Restore the previous selection. 
    rtxtOutputText.SelectionStart = PreviousPosition 
    rtxtOutputText.SelectionLength = PreviousSelection 
End Sub 

感謝Plutonix告訴我處置字體。

+1

最好是定義高亮/選定/特殊的Font *一次,然後重複使用它的同一個實例。字體是IDisposable – Plutonix

+0

@Plutonix:你當然是對的!我想過這樣做,但改變了我的想法:)。另外,是否可以在不影響控制的情況下安全地處理新的字體對象?或者我應該像字符串實例一樣定義它? –

+0

你可以把它放在'Using'塊中,但爲什麼一遍又一遍地創建相同的新字體? – Plutonix

相關問題