4

I want to get a list of all data from the clipboard history but I can't find an enumerator method. Would there be something I'm missing or what other way can I do it? I can't find an enumerator method in the clipboard class.

var clip = Clipboard.GetDataObject();

foreach (var item in clip)
{
    MessageBox.Show(item);
}
Wes
  • 1,847
  • 1
  • 16
  • 30
  • I don't know how the *Clipboard history* works, but the `Clipboard` class is a rather slim wrapper around the traditional Windows `IDataObject` clipboard implementation. When a programs puts somthing on the clipboard, it can contain one or more clipboard formats (for example, Excel may put copied data on the clipboard as text, as a table, as an Excel-specific object, and as an image in ore or more formats). The consumer of the clipboard can interrogate the formats and decide which format makes the most sense. Doing `Clipboard.GetText` is easy, if you want to deal with other formats, it's more – Flydog57 Dec 20 '20 at 22:52
  • 1
    Call the IDataObject's `GetFormats(false)` method, then use that collection as *enumerator*, retrieving the data for all formats it includes (`IDataObject.GetData(string, bool)`). It's a long ride... – Jimi Dec 20 '20 at 22:54
  • @Flydog57 I've seen examples on how to deal with multiple formats but `GetText` only returns the last item copied, not a list. – Wes Dec 20 '20 at 22:58
  • @Jimi I've tried that already. `GetFormats` only returns the list of formats for the last item copied, not for the rest of items. – Wes Dec 20 '20 at 23:01
  • 2
    Are you referring to the Clipboard History in Windows 10 (`WIN + V`, when enabled)? You need WinRT API to access those objects (in a managed way). – Jimi Dec 20 '20 at 23:09
  • @Jimi Yes but how would I do that in wpf? – Wes Dec 20 '20 at 23:14
  • 1
    [Call Windows Runtime APIs in desktop apps](https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/desktop-to-uwp-enhance) – Jimi Dec 20 '20 at 23:15
  • @clutcher: that was my point, the `Clipboard` class only deals with the traditional Windows clipboard. It knows nothing of history – Flydog57 Dec 21 '20 at 01:16

1 Answers1

7

I was able to get clipboard history by referencing the Clipboard class from WinRT API onto my WPF application.

using Clipboard = Windows.ApplicationModel.DataTransfer.Clipboard;

Task.Run(async () => {
    var items = await Clipboard.GetHistoryItemsAsync();
    foreach (var item in items.Items)
    {
        string data = await item.Content.GetTextAsync();
        MessageBox.Show(data);
    }
});

I also had to set my target framework to .NET 5.0 with a TFM version and didn't need any NuGet packages for this to work. You will need the Microsoft.Windows.SDK.Contracts NuGet Package on earlier versions of .NET.

<TargetFramework>net5.0-windows10.0.19041.0</TargetFramework>
Wes
  • 1,847
  • 1
  • 16
  • 30