簡體   English   中英

如何使用winforms在c#中的richtextbox中獲取某行的字體大小

[英]how to get the fontsize of a certain line in a richtextbox in c# using winforms

我有 2 個用於字體和字體大小的組合框。 當我單擊它們時,它會更改我的 Richtextbox 中的字體大小或字體。 現在我希望它像在 word 中一樣工作。 如果您剛移動到的行的字體或大小不同。 它應該檢測到並更改組合框以匹配當前行的字體和大小。 Somoeone 其他人問了同樣的問題並得到了對我不起作用的結果。 如下

    private void richTextBox1_SelectionChanged(object sender, EventArgs e)
    {
        MessageBox.Show("we got here"); // this is my added part to let me know if the code is even getting executed. It is not.
        richTextBox1.SelectionStart = 1;
        richTextBox1.SelectionLength = 1;
        comboBox1.Text = richTextBox1.SelectionFont.ToString();
        comboBox2.Text = null;
        comboBox2.Text = richTextBox1.SelectionFont.Size.ToString();

    }

我一直希望這是我的答案,但我看不出在沒有選擇任何內容時 SelectionFont 會有什么不同。 當我使用向上/向下箭頭在文檔中移動時,似乎沒有調用 richTextBox1_SelectionChanged 事件。 問題不在於組合框,問題在於當我通過我的文檔箭頭時,我需要能夠知道插入符號位置的字體和大小,以便它可以觸發事件來更改組合框以匹配。

您使用的代碼將始終從索引1處的字符中進行選擇,並且長度為1 相反,您需要使用它會為您提供以下代碼而不指定選擇(因此它將從 ritchTextBox 中獲取選擇)。

string fontName = richTextBox1.SelectionFont.Name;
float fontsize = richTextBox1.SelectionFont.Size;

您應該將新組合框位置的值臨時保存在變量中,否則如果直接執行

comboBox1.SelectedIndex = comboBox1.FindStringExact(richTextBox1.SelectionFont.Name);

將立即調用 comboBox1_SelectedIndexChanged 事件並可能影響結果。

所以試試吧:

private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
    int comboBox1Index = comboBox1.FindStringExact(richTextBox1.SelectionFont.Name);
    int comboBox2Index = comboBox2.FindStringExact(richTextBox1.SelectionFont.Size.ToString());

    comboBox1.SelectedIndex = comboBox1Index;
    comboBox2.SelectedIndex = comboBox2Index;
}

我改編了 Sujith 的解決方案和 Markus 解決方案的一半,並提出了以下對我來說很好用的方法:

Private Sub Description_SelectionChanged(sender As Object, e As EventArgs) Handles Description.SelectionChanged

    Dim fontName As String = Description.SelectionFont.Name
    Dim fontSize As Single = Description.SelectionFont.Size

    tbSelectFont.Text = fontName
    tbSelectSize.Text = fontSize

End Sub

暫無
暫無

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

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