Justin Drury
Justin Drury

Reputation: 748

Easiest way to format rtf/unicode/utf-8 in a RichTextBox?

I'm currently beating my head against a wall trying to figure this out. But long story short, I'd like to convert a string between 2 UTF-8 '\u0002' to bold formating. This is for an IRC client that I'm working on so I've been running into these quite a bit. I've treid regex and found that matching on the rtf as ((\'02) works to catch it, but I'm not sure how to match the last character and change it to \bclear or whatever the rtf formating close is.

I can't exactly paste the text I'm trying to parse because the characters get filtered out of the post. But when looking at the char value its an int of 2.

Here's an attempt to paste the offending text:

[02:34] test test

Upvotes: 1

Views: 4725

Answers (2)

Pat
Pat

Reputation: 16891

I don't have a test case, but you could also probably use the Clipboard class's GetText method with the Unicode TextDataFormat. Basically, I think you could place the input in the clipboard and get it out in a different format (works for RTF and the like). Here's MS's demo code (not applicable directly, but demonstrates the API):

// Demonstrates SetText, ContainsText, and GetText. 
public String SwapClipboardHtmlText(String replacementHtmlText)
{
    String returnHtmlText = null;
    if (Clipboard.ContainsText(TextDataFormat.Html))
    {
        returnHtmlText = Clipboard.GetText(TextDataFormat.Html);
        Clipboard.SetText(replacementHtmlText, TextDataFormat.Html);
    }
    return returnHtmlText;
}

Of course, if you do that, you probably want to save and restore what was in the clipboard, or else you may upset your users!

Upvotes: 0

Daniel LeCheminant
Daniel LeCheminant

Reputation: 51081

You could use either

rtb.Rtf = Regex.Replace(rtb.Rtf, @"\\'02\s*(.*?)\s*\\'02", @"\b $1 \b0");

or

rtb.Rtf = Regex.Replace(rtb.Rtf, @"\\'02\s*(.*?)\s*\\'02", @"\'02 \b $1 \b0 \'02");

depending on whether you want to keep the \u0002s in there.

The \b and \b0 turn the bold on and off in RTF.

Upvotes: 1

Related Questions