windows 如何从剪贴板检索数据作为 System.String[]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3840080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to retrieve data from clipboard as System.String[]
提问by xtofl
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:
当我从应用程序复制数据时,我编写了一个简单的 C# 脚本来检查它是什么类型。显然(我也预料到了),它是一个字符串数组:
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?
为什么?我如何提取数据?
回答by Isak Savo
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 formatswhich many programs use.
您不应该将 CLR 类型作为参数。GetData 的参数只是一个标识符,可以是任何东西,但有一些许多程序使用的预定义格式。
What you probably want to do is use DataFormats.Textto 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.
您可能想要做的是使用DataFormats.Text以文本形式(即字符串)检索数据。请注意,这仅在剪贴板内容的来源实际以这种格式提供数据时才有效,但大多数这样做应该是安全的。
And, since text is such a common format, there's even a convenience method to retrieve it in that format called Clipboard.GetText()
而且,由于文本是一种如此常见的格式,甚至有一种方便的方法可以以该格式检索它,称为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.
编辑:调用 GetFormats 时返回的 string[] 只是一个列出所有可用格式的字符串数组。它不是实际的剪贴板数据,它只是告诉您在执行obj.GetData()
. 在调试器中查看该数组或在 foreach 中打印它以查看是否有任何类似数组的格式。
回答by Ivan Feri?
data.GetFormats(true)
by MSDNreturns 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:
data.GetFormats(true)
通过MSDN返回的,与所有的数据格式,在剪贴板这些格式可以被转换为沿着存储剪贴板内的数据格式的名称。要获取数据,您需要调用data.GetData(dataFormatName)
您想要获取的数据格式。如果你想获得所有的对象,你应该这样做:
foreach (var item in data.GetFormats(true))
{
object o = data.GetData(item);
// do something with o
}