以c#windows形式突出显示文本到语音

本文关键字:显示 文本 语音 c#windows | 更新日期: 2023-09-27 18:30:07

在c#windows窗体中发言时,如何突出显示文本?试过这个:

public void HighlightWordInRichTextBox(System.Windows.Forms.RichTextBox richTextBox,string word, SolidColorBrush color)
{
    //clear all formatings
    //System.Windows.Controls.RichTextBox  rt= (System.Windows.Controls.RichTextBox.ichTextBox;
   TextRange textRange = new TextRange(richTextBox.SelectionStart, richTextBox.Document.ContentEnd);
    textRange.ApplyPropertyValue(TextElement.BackgroundProperty, null);
    //Current word at the pointer
    TextRange tr = FindWordFromPosition(textPointer,word);
    if (!object.Equals(tr, null))
    {
        //set the pointer to the end of "word"
        textPointer = tr.End;
        //apply highlight color
        tr.ApplyPropertyValue(TextElement.BackgroundProperty, color);
     }
}
public TextRange FindWordFromPosition(TextPointer position, string word)
{
    while (position != null)
    {
        if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
        {
            string textRun = position.GetTextInRun(LogicalDirection.Forward);
            // Find the starting index of any substring that matches "word".
            int indexInRun = textRun.IndexOf(word);
            if (indexInRun >= 0)
            {
                TextPointer start = position.GetPositionAtOffset(indexInRun);
                TextPointer end = start.GetPositionAtOffset(word.Length);
                return new TextRange(start, end);
            }
        }
        position = position.GetNextContextPosition(LogicalDirection.Forward);
    }
    // position will be null if "word" is not found.
    return null;
}
void reader_SpeakProgress(object sender, SpeakProgressEventArgs e)
{
    //show the synthesizer's current progress 
    label2.Text= e.Text;
    SolidColorBrush highlightColor = new SolidColorBrush(Colors.Yellow);
    HighlightWordInRichTextBox(richTextBox1, e.Text, highlightColor);
}

但是这个代码中有错误在文档中出错:

"system.windows.forms.richtextbox"不包含"document"的定义,也找不到接受类型为"system.windows.forms.richtextbox"的第一个参数的扩展方法"document"(是否缺少using指令或程序集引用?)

以c#windows形式突出显示文本到语音

您已经将WPF代码用于WinForms控件。WPF的RichTextBox确实有Document属性,但WinForms没有。

你可能正在寻找这样的东西:

new TextRange(richTextBox.SelectionStart, richTextBox.SelectionLength);