Reputation: 684
I have used the following code to change some formatting from the text copied from a RTB on the fly using the clipboard
public static void CustomCopy(RichTextBox rtb)
{
rtb.Copy();
var _inMemoryRtb=new RichTextBox();
var iData = Clipboard.GetDataObject();
if (iData.GetDataPresent(DataFormats.Rtf))
{
_inMemoryRtb.Rtf = (string)Clipboard.GetData(DataFormats.Rtf);
_inMemoryRtb.SelectAll();
_inMemoryRtb.SelectionBackColor = Color.Red;
Clipboard.SetData(DataFormats.Rtf, _inMemoryRtb.Rtf);
}
_inMemoryRtb.Clear();
}
When I paste the copied text to Word/Wordpad it works but if I paste to a browser/notepad nothing happens. Where is the issue ?
Upvotes: 0
Views: 1405
Reputation:
You cannot get what you want without relying on "RTF-supporting environment", like Word. DataFormats.Rtf
in Clipboard.SetData
avoids any RTF-non-supporting program to not be able to deal with this data.
A RichTextBox
and the text in it tends to be easily misundestood as text + something else, but it is a completely different format. A quick experiment to understand this better: replace in your code Clipboard.SetData(DataFormats.Rtf, _inMemoryRtb.Rtf);
with Clipboard.SetData(DataFormats.Text, _inMemoryRtb.Rtf);
. What you see now is what the un-codified version of the RTF content, what any program is able to see. Bear in mind that his un-understandable text can be converted back into RTF quite easily:
Clipboard.SetData(DataFormats.Text, _inMemoryRtb.Rtf);
var iData2 = Clipboard.GetDataObject();
rtb.Rtf = (string)Clipboard.GetData(DataFormats.Text);
UPDATE
With your code, you are pasting RTF information (which cannot be dealt with by a non-RTF-supporting program, like Notepad). If you want to just paste the text in rtb
, rely on SetText
: you will store in the ClipBoard
the text you want to paste (independently upon the given format) and this information will be "understood" by any program.
Clipboard.SetText(rtb.Text, TextDataFormat.Text);
CLARIFICATION
The original OP's code was copying RTF information, what cannot be understood by non-RTP-supporting programs. This code works under the right conditions (RTF supported by source and destination programs). The previous update refers to copying just text regardless of format. Thus, if what you want is to copy RTF-formatted text when possible (RichTextBox to RichTextBox) and just text otherwise (RichTextBox to Notepad), you should write both codes together (original OP's one and aforementioned SetText
).
Upvotes: 1