Clipboard behaves differently in .NET 3.5 and 4, but why?

限于喜欢 提交于 2019-12-03 01:16:44

I repro. You can get more insight into the bug with Debug + Exceptions, tick the Thrown checkbox for CLR exceptions. That will stop the program when an internal exception is thrown by the clipboard code in the framework. The IDataObject.GetDataHere() implementation method fails with a COM exception, "Invalid FORMATETC structure (Exception from HRESULT: 0x80040064 (DV_E_FORMATETC))".

There is something wrong with the format. That becomes clear when you set a breakpoint after the Clipboard.SetDataObject(obj) statement. And put Clipboard.GetDataObject().GetFormats() in a debugger watch expression. I see:

"System.Collections.Generic.List`1[[ClipboardTest.Program+Element, ConsoleApplication1, Version=1.0.0.0, Culture=neutral, Public"

Note how the string is truncated, the PublicKeyToken part got mangled. You can arbitrarily alter this truncated string by changing the namespace name and the project name. Make them short enough and the program won't fail.

Clearly this is the cause of the problem. The string length is clipped to 127 characters, any type whose full name is longer than that is going to cause this failure. With a high likelihood that this will be a generic type since they have very long names.

Please report this bug at connect.microsoft.com. Your code demonstrates the bug very well, just posting a link to it in your bug report will be sufficient. I don't have a very good workaround, ensuring the name is short enough is not very practical. But you can with code like this:

        // Put it on the clipboard, use a wrapper type with a short name
        var envelope = new List<object>();
        envelope.AddRange(obj);
        Clipboard.SetDataObject(envelope);

        // Retrieve from clipboard, unwrap back to original type
        envelope = (List<object>)Clipboard.GetDataObject().GetData(typeof(List<object>));
        var retval = new List<Element>();
        retval.AddRange(envelope.Cast<Element>());
        return retval;

UPDATE: this bug is reported fixed in VS2013.

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