6

我想获取当前存储在 Windows 剪贴板中的数据并将其保存在一个变量中,然后将数据放回剪贴板。

现在我正在使用这段代码:

object l_oClipBrdData = Clipboard.GetDataObject();
Clipboard.SetDataObject(l_oClipBrdData ,true);

但是在这样做之后剪贴板是空的。

我究竟做错了什么?

4

4 回答 4

5

这是一个演示“剪贴板”对象的示例:

string text;
string[] a;

if (Clipboard.ContainsText())
   {
      text = Clipboard.GetText(TextDataFormat.Text);

      //  the following could have been done simpler with
      //  a Regex, but the regular expression would be not
      //  exactly simple

      if (text.Length > 1)
          {
              //  unify all line breaks to \r
              text = text.Replace("\r\n", "\r").Replace("\n", "\r");

              //  create an array of lines
              a = text.Split('\r');

              //  join all trimmed lines with a space as separator
              text = "";

              //  can't use string.Join() with a Trim() of all fragments
              foreach (string t in a)
              {
                  if (text.Length > 0)
                      text += " ";
                  text += t.Trim();
              }

            Clipboard.SetDataObject(text, true);
          }
    }
于 2013-01-31T21:48:19.100 回答
3

Clipboard.GetDataObject() will return the IDataObject from the clipboard, if you want to get the actual data you can call GetData(typeof(dataType))

Example:

        int mydata = 100;

        Clipboard.SetDataObject(mydata, true);

        var clipData = Clipboard.GetDataObject().GetData(typeof(int)); 

There are also a lot of predifined dataTypes you can use

Example:

        if (Clipboard.ContainsData(DataFormats.Bitmap))
        {
            var clipData = Clipboard.GetData(DataFormats.Bitmap);
        }
于 2013-01-31T21:57:20.633 回答
1

传递给 SetDataObject() 的对象应该支持序列化。如果这是您自己的类型,请使用 [Serializable] 属性对其进行标记。

更多信息:

http://msdn.microsoft.com/en-gb/library/cs5ebdfz(v=vs.90).aspx

http://www.codeproject.com/Articles/8102/Saving-and-obtaining-custom-objects-to-from-Window

于 2013-01-31T21:44:27.977 回答
0

Clipboard.Flush();之后尝试调用SetDataObject()

于 2014-06-20T17:18:31.087 回答