How to retrieve data from clipboard as System.String[]

泪湿孤枕 提交于 2020-01-13 07:19:15

问题


When I copy data from my application, I wrote a simple C# script to check what type it is. Apparently (and I expected that), it's an array of strings:

       IDataObject data = Clipboard.GetDataObject();
       Console.WriteLine(data.GetFormats(true)); // writes "System.String[]"

Now when I extract the data like

      object o = data.GetData( "System.String[]" );

the resulting object stays null.

Why? How am I to extract the data?


回答1:


You are not supposed to put the CLR types as parameters. The parameter to GetData is just an identifier that can be anything, but there are some pre-defined formats which many programs use.

What you probably want to do is use DataFormats.Text to retrieve the data in text form (i.e. a string). Note that this only works if the source of the clipboard contents actually provided data in this format, but most do so you should be safe.

And, since text is such a common format, there's even a convenience method to retrieve it in that format called Clipboard.GetText()

EDIT: The string[] you get back when you call GetFormats is just an array of strings listing all the available formats. It's not the actual clipboard data, it just tells you which format you can get it in when you do obj.GetData(). Look at that array in the debugger or print it in a foreach to see if there's any format that is array-like.




回答2:


data.GetFormats(true) by MSDN returns names of data formats that are stored inside the clipboard along with all data formats that those formats in clipboard can be converted to. To get data you need to call data.GetData(dataFormatName) of data format you want to get. If you want to get all the objects you should do this:

foreach (var item in data.GetFormats(true))
{
   object o = data.GetData(item);
   // do something with o
}


来源:https://stackoverflow.com/questions/3840080/how-to-retrieve-data-from-clipboard-as-system-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!