How do I backup and restore the system clipboard in C#?

后端 未结 2 477
死守一世寂寞
死守一世寂寞 2020-11-27 07:57

I will do my best to explain in detail what I\'m trying to achieve.

I\'m using C# with IntPtr window handles to perform a CTRL-C copy operation on an external appli

相关标签:
2条回答
  • 2020-11-27 08:21

    You could save the content of the clipboard in a dictionary, and restore it afterwards :

    public IDictionary<string, object> GetClipboardData()
    {
        var dict = new Dictionary<string, object>();
        var dataObject = Clipboard.GetDataObject();
        foreach(var format in dataObject.GetFormats())
        {
            dict.Add(format, dataObject.GetData(format));
        }
        return dict;
    }
    
    public void SetClipboardData(IDictionary<string, object> dict)
    {
        var dataObject = Clipboard.GetDataObject();
        foreach(var kvp in dict)
        {
            dataObject.SetData(kvp.Key, kvp.Value);
        }
    }
    
    ...
    
    var backup = GetClipboardData();
    // Do something with the clipboard...
    ...
    SetClipboardData(backup);
    
    0 讨论(0)
  • 2020-11-27 08:25

    It's folly to try to do this. You cannot faithfully restore the clipboard to its prior state. There could be dozens of unrendered data formats present using "delayed rendering", and if you attempt to render them all, you'll cause the source app to run out of resources. It's like walking into a resturaunt and saying "give me one of everything".

    Suppose that the user has selected 500 rows x 100 columns in Excel, and has copied that to the clipboard. Excel "advertises" that it can produce this data in about 25 different formats, including Bitmap. Once you paste it as a Bitmap, you force Excel to render it as a bitmap. That's 50000 cells, and would be a bitmap approx 10,000 x 15,000 pixels. And you expect the user to wait around while Excel coughs that up, along with 24 other formats? Not feasible.

    Furthermore, you're going to be triggering WM_DrawClipboard events, which will impact other clipboard viewers.

    Give up.

    0 讨论(0)
提交回复
热议问题