c# - 检查 richtextbox 上的选定文本是否全部为粗体

标签 c# .net winforms richtextbox

如何检查 richtextbox 上的选定文本是否全部为粗体。例如:

asdasdasdasd ← 这不是全部加粗
我很大胆 ←这很大胆

这是我编写的代码,它可以检查它是否全部为粗体但速度很慢,因为它使用 Selection.StartSelection.Length< 一个一个地检查字符 并检查是否为粗体。

bool allbold = true;
int start = richTextBox1.SelectionStart;
int end = richTextBox1.SelectionLength;
for (int i = 1; i < end; i++)
{
    richTextBox1.SelectionStart = start+i;
    richTextBox1.SelectionLength = 1;
    if (!richTextBox1.SelectionFont.Bold)
    {
        allbold = false;
        richTextBox1.SelectionStart = 0;
        richTextBox1.SelectionLength = 0;
        richTextBox1.SelectionStart = start;
        richTextBox1.SelectionLength = end;
        richTextBox1.Focus();
    }
}

还有比这更有效的方法吗?

最佳答案

您可以检查richTextBox1.SelectionFont.Bold。如果所有选定的文本都是粗体,则返回 true。


为了测试,用这样的值初始化RichTextBox就足够了:

richTextBox1.SelectedRtf = @"{\rtf1\fbidis\ansi\ansicpg1256\deff0" +
    @"\deflang1065{\fonttbl{\f0\fnil\fcharset0 Calibri;}}\uc1\pard\ltrpar" +
    @"\lang9\b\f0\fs72 T\fs22 his\b0  \b i\b0 s a \b t\b0 est.}";

然后以这种方式检查不同的选择:

if (richTextBox1.SelectionFont != null)
    MessageBox.Show(string.Format("{0}", richTextBox1.SelectionFont.Bold));

关于c# - 检查 richtextbox 上的选定文本是否全部为粗体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40049981/

相关文章:

c# - DataGridView 中的图像问题

c# - 如何使用 SvcUtil.exe 生成 WCF 服务

c# - Linq 计数(条件)未按预期工作

.net - WPF 中的 DataRepeater 控件?

c# - 请向我解释这个 BackgroundWorker 事件

c# - 更改应用程序的图标 : Works in Title Bar, 但不在任务栏或开始菜单中

c# - 找不到任何已安装的.NET Core SDK

c# - 提取渐变画笔属性

c# - 在 C# 或 VB.Net 中创建内存泄漏

c# 将连接项的列表排序为多个列表