问题
How to check if selected text on richtextbox that
its chars is not all bold.
For example:
notboldboldnotbold ← this is mixed.
Im not all bold ← this is not all bold
This is the code I have made, it checks selected text on richtextbox whether the text contains some bolded text or not.
its slow because its checking the char one by one using Selection.Start to Selection.Length and check if bold. If I use richTextBox1.SelectionFont.Bold
it will return false because its not all bold, that means also if its mixed with bold and not bold.
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();
}
}
When checking long string, I can see the text is getting bolded when checking. Is there any efficient way than this?
回答1:
In an RTF text, \b
indicates start of a bold part of text. So you can first check if richTextBox1.SelectionFont.Bold
is true, then it means the text is all bold, otherwise, if the selected rtf contains \b
it means the content is mixes, otherwise there is no bold text in selected text:
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");
}
To test the solution, it's enough to initialize the RichtextBox
with such value:
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}";
来源:https://stackoverflow.com/questions/40054607/check-if-selected-text-on-richtextbox-is-not-all-bold-or-mixed-c