Reputation: 69979
I found a similar question in this post, but my problem is different, so worthy of a new post.
Basically, I have a WPF/C# application that generates a text output. The text output includes several instances of a special '℗' character. The user can click a button to be sent the information in an e-mail and this part works fine. The user can click another button in the application to copy the same text output into the clipboard and this is where I have a problem. I am using the following code to copy/paste the text.
public void SetClipboardText(string text)
{
try { Clipboard.SetData(DataFormats.Text, text); }
catch (COMException)
{
MessageBox.Show("The clipboard was inaccessible, please try again later");
}
}
public string GetClipboardText()
{
if (Clipboard.ContainsData("Text"))
{
try { return Clipboard.GetData(DataFormats.Text) as string; }
catch (COMException)
{
MessageBox.Show("The clipboard was inaccessible, please try again later");
}
}
return string.Empty;
}
When the copied text is pasted into any external text-editing application, the '℗' character is replaced with a '?' character. After searching the internet, I found another article relating to a similar problem regarding encoding HTML before copying to the clipboard. However, after adding the following line of code as the first line in the SetClipboardText
method, the pasted '℗' character is now replaced with 'â„—' in the output.
text = Encoding.GetEncoding(0).GetString(Encoding.UTF8.GetBytes(text));
This tells me that this is an encoding issue. So my question really is, 'which character encoding can I use to successfully copy AND paste a '℗' character?'. As you can see from all the '℗' characters in this post, it is indeed possible to copy and paste them using the clipboard... but how?
Additional information:
The '℗' character comes from the Arial font included in all Windows PCs and can also be found in the 'normal text' Font in Word. After typing (int)'℗'
in the Visual Studio QuickWatch Window, I get the relating integer value of 8471 for the character.
Solution Update:
Thanks to @Ilya Ivanov, I have changed the copy/paste code to the following, which now copies and pastes special characters successfully.
public void SetClipboardText(string text)
{
try { Clipboard.SetText(text); }
catch (COMException)
{
MessageBox.Show("The clipboard was inaccessible, please try again later");
}
}
public string GetClipboardText()
{
if (Clipboard.ContainsText())
{
try { return Clipboard.GetText(); }
catch (COMException)
{
MessageBox.Show("The clipboard was inaccessible, please try again later");
}
}
return string.Empty;
}
Upvotes: 0
Views: 5275
Reputation: 23636
Try to use Clipboard.SetText("℗", TextDataFormat.UnicodeText);
instead of Clipboard.SetData
. It works with special symbols like ℗
I've executed this code in LinqPad
and the pasted text from clipboard into text editor - worked fine.
Upvotes: 6