2

When trying to copy to the clipboard, what is the difference between

Clipboard.SetData(DataFormats.Text, "");

and

Clipboard.SetText("");
Paul Nikonowicz
  • 3,825
  • 18
  • 37

4 Answers4

2

SetText is simply a convenience method for SetData, only with SetText using UnicodeText versus yours, which is ANSI

From source:

    public static void SetText(string text)
    { 
        ....
        SetText(text, TextDataFormat.UnicodeText); //<------------
    }

    public static void SetText(string text, TextDataFormat format) 
    {
        ....
        SetDataInternal(DataFormats.ConvertToDataFormats(format), text);
    }

    public static void SetData(string format, object data) 
    {
        ....
        SetDataInternal(format, data);
    } 

So, both use SetDataInternal

Justin Pihony
  • 62,016
  • 17
  • 131
  • 162
2

The format Text that you use does not specify that it's Unicode. As we can see in the source code, SetText calls SetDataInternal(DataFormats.UnicodeText, data) while your second example calls SetDataInternal(DataFormats.Text, data).

The DataFormats.Text specifies ANSI encoding. It basically means speciál characters get replaced by some ? or similar. Read more about this format in this other question/answer: What is ANSI format?

Community
  • 1
  • 1
Bas
  • 25,270
  • 7
  • 45
  • 82
1

The documentation says what Clipboard.SetText() does:

Stores UnicodeText data on the Clipboard.

That suggests that Clipboard.SetText("") is equivalent to Clipboard.SetData(DataFormats.UnicodeText, "");

So, to answer your question, Clipboard.SetText("") puts an empty unicode text string into the clipboard, while Clipboard.SetData(DataFormats.Text, ""); stores there an empty ANSI text string.

kdojeteri
  • 685
  • 6
  • 17
0

The difference between setting Text and Data of Text really there are none. When setting the clipboard, for example you could set the clipboard to a Folder so the user could copy and paste files, or text. So setting the data type for the clip board is required, but if you use the preset function SetText it was created to save the programmer time by not having to do so.

this code Clipboard.SetData(DataFormats.Text, ""); is the same as Clipboard.SetText(""); except inside the function SetText(String text) it will set the data format for you, the code inside SetText (after decompilation) is

public static void SetText(string text, TextDataFormat format)
{
   if (string.IsNullOrEmpty(text))
   {
      throw new ArgumentNullException("text");
   }
   if (!System.Windows.Forms.ClientUtils.IsEnumValid(format, (int) format, 0, 4))
   {
      throw new InvalidEnumArgumentException("format", (int) format, typeof(TextDataFormat));
   }
   System.Windows.Forms.IDataObject data = new DataObject();
   data.SetData(ConvertToDataFormats(format), false, text);
   SetDataObject(data, true);
}
Callum
  • 675
  • 6
  • 17