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

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

响应格式属性的变化

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

    下面的示例假定窗体包含一个 RichTextBox 控件和一个 ToolBar 包含工具栏按钮的控件。 有关工具栏和工具栏按钮的详细信息,请参阅 How to: Add Buttons to a ToolBar Control.

    ' 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;
          }
       }
    

另请参阅