Search code examples
c#.net-coreuwpwindows-runtimeclipboarddata

How to copy multiple items to clipboard history in c#?


I'm using the clipboard class from Win API (Windows.ApplicationModel.DataTransfer.Clipboard). When I try to copy multiple items one by one to the clipboard history, it gets overwritten by the recent item. I want to store every item I copy onto the clipboard history. My clipboard history is enabled and I tried using all of the set methods from clipboard including the SetText method from (System.Windows.Clipboard) and all of which overwrites instead of adding to history.

    private void UpdateClipboardOnProfileDropDownClosed(object sender, EventArgs e)
    {
        Clipboard.ClearHistory();
        using (var db = new LiteDatabase(Path.Combine(documents, "Auto Paste Clipboard", "data.db")))
        {
            var collection = db.GetCollection<ClipboardProfile>("clipboard");

            var clipboard = collection.FindOne(x => x.Profile == ProfileComboBox.Text);

            clipboard.Clipboard.Reverse();

            MessageBox.Show(clipboard.Clipboard.Count.ToString());
            foreach (var item in clipboard.Clipboard)
            {
                DataPackage data = new DataPackage
                {
                    RequestedOperation = DataPackageOperation.Copy
                };

                data.SetText(item);                          
                Clipboard.SetContent(data);
            }                                
        }
    }

Solution

  • It takes some delays for Clipboard history to save the current item. Therefore, you could try to add a delay when an item is added.

    Please check the following code as a sample:

    private async void Button_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
    {
        if(Clipboard.IsHistoryEnabled())
        {
            List<string> lists=new List<string>{ "1","2","3","4","5","6","7","8","9","10"}; 
            foreach(var item in lists)
            {
                DataPackage dataPackage = new DataPackage();
                dataPackage.SetText(item);
                Clipboard.SetContent(dataPackage);
                await Task.Delay(250);
            }
        }
    }
    

    Note, if these items are not all added, you could increase the delay time.