检查richtextbox上的选定文本是否全部粗体或混合[c#]
本文关键字:混合 全部 是否 richtextbox 文本 检查 | 更新日期: 2023-09-27 18:13:13
如何检查richtextbox上的选定文本
例如:它的字符不全是粗体。
notboldboldnotbold←这是混合的。
我不是全部加粗←这不是全部加粗
这是我所做的代码,它检查richtextbox上的选定文本是否包含一些粗体文本。
比较慢,因为它使用select逐个检查char。开始选择。长度并检查是否加粗。如果我使用richTextBox1.SelectionFont.Bold
,它将返回false,因为它不是全部粗体,这也意味着如果它混合了粗体和非粗体。
bool notallbold = 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)
{
notallbold = false;
richTextBox1.SelectionStart = 0;
richTextBox1.SelectionLength = 0;
richTextBox1.SelectionStart = start;
richTextBox1.SelectionLength = end;
richTextBox1.Focus();
}
}
当检查长字符串时,我可以看到文本在检查时被加粗。还有比这更有效的方法吗?
在RTF文本中,'b
表示文本中粗体部分的开始。因此,您可以首先检查richTextBox1.SelectionFont.Bold
是否为真,则意味着文本都是粗体,否则,如果选定的rtf包含'b
,则意味着内容是混合的,否则在选定的文本中没有粗体文本:
private void button1_Click(object sender, EventArgs e)
{
if (richTextBox1.SelectionFont == null)
return;
if (richTextBox1.SelectionFont.Bold)
MessageBox.Show("All text is Bold");
else if (richTextBox1.SelectedRtf.Replace(@"''", "").IndexOf(@"'b") > -1)
MessageBox.Show("Mixed Content");
else
MessageBox.Show("Text doesn't contain Bold");
}
要测试这个解决方案,用这样的值初始化RichtextBox
就足够了:
this.richTextBox1.SelectedRtf = @"{'rtf1'fbidis'ansi'ansicpg1256'deff0'deflang1065" +
@"{'fonttbl{'f0'fnil'fcharset0 Calibri;}}'uc1'pard'ltrpar" +
@"'lang9'b'f0'fs22 T'b0 his is a 'b test}";