CLIPBRD_E_CANT_OPEN error when setting the Clipboard from .NET

前端 未结 7 1204
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 08:08

Why does the following code sometimes causes an Exception with the contents \"CLIPBRD_E_CANT_OPEN\":

Clipboard.SetText(str);

This usually o

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 08:28

    Actually there could be another issue at hand. The framework call (both the WPF and winform flavors) to something like this (code is from reflector):

    private static void SetDataInternal(string format, object data)
    {
        bool flag;
        if (IsDataFormatAutoConvert(format))
        {
            flag = true;
        }
        else
        {
            flag = false;
        }
        IDataObject obj2 = new DataObject();
        obj2.SetData(format, data, flag);
        SetDataObject(obj2, true);
    }
    

    Note that SetDataObject is always called with true in this case.

    Internally that triggers two calls to the win32 api, one to set the data and one to flush it from your app so it's available after the app closes.

    I've seen several apps (some chrome plugin, and a download manager) that listen to the clipboard event. As soon as the first call hits, the app will open the clipboard to look into the data, and the second call to flush will fail.

    Haven't found a good solution except to write my own clipboard class that uses direct win32 API or to call setDataObject directly with false for keeping data after the app closes.

提交回复
热议问题