如何:确定何时在 Windows 窗体 RichTextBox 控件中更改格式属性

Windows 窗体 RichTextBox 控件的常见用途是使用字体选项或段落样式等属性设置文本的格式。 应用程序可能需要跟踪文本格式的任何更改,以便显示工具栏,就像许多字处理应用程序一样。

响应格式设置属性的更改

  1. SelectionChanged 事件处理程序中编写代码,根据属性的值执行适当的操作。 以下示例根据 SelectionBullet 属性的值更改工具栏按钮的外观。 只有在控件中移动插入点时,工具栏按钮才会更新。

    下面的示例假定窗体具有 RichTextBox 控件和包含工具栏按钮的 ToolBar 控件。 有关工具栏和工具栏按钮的详细信息,请参阅 如何:向工具栏控件添加按钮

    ' The following code assumes the existence of a toolbar control  
    ' with at least one toolbar button.  
    Private Sub RichTextBox1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.SelectionChanged  
       If RichTextBox1.SelectionBullet = True Then  
          ' Bullet button on toolbar should appear pressed  
          ToolBarButton1.Pushed = True  
       Else  
           ' Bullet button on toolbar should appear unpressed  
           ToolBarButton1.Pushed = False  
       End If  
    End Sub  
    
    // The following code assumes the existence of a toolbar control  
    // with at least one toolbar button.  
    private void richTextBox1_SelectionChanged(object sender,  
    System.EventArgs e)  
    {  
       if (richTextBox1.SelectionBullet == true)
       {  
          // Bullet button on toolbar should appear pressed  
          toolBarButton1.Pushed = true;  
       }  
       else
       {  
          // Bullet button on toolbar should appear unpressed  
          toolBarButton1.Pushed = false;  
       }  
    }  
    
    // The following code assumes the existence of a toolbar control  
    // with at least one toolbar button.  
    private:  
       System::Void richTextBox1_SelectionChanged(  
          System::Object ^  sender, System::EventArgs ^  e)  
       {  
          if (richTextBox1->SelectionBullet == true)  
          {  
             // Bullet button on toolbar should appear pressed  
             toolBarButton1->Pushed = true;  
          }  
          else  
          {  
             // Bullet button on toolbar should appear unpressed  
             toolBarButton1->Pushed = false;  
          }  
       }  
    

另请参阅