如何将 IDataObject 值复制到另一个 IDataObject?

How to copy IDataObject value to another IDataObject?

我想在 C# 中从 'd' IDataObject 到 'c' IDataObject 获取值,但是即使我不单击 D 键,我的 'c' 也拥有剪贴板中的值。如何将一个 IDataObject 的独立值赋予第二个?

第一个函数:

if (Keyboard.IsKeyDown(Key.D))
{
    d = Clipboard.GetDataObject();
    c = d;      // <-- doesn't work
    string dd = d.GetData(DataFormats.Text).ToString();      //content
    MessageBox.Show(dd);
}

第二个函数

if (Keyboard.IsKeyDown(Key.S))
{
    string dd = c.GetData(DataFormats.Text).ToString();      //content
    MessageBox.Show(dd);
}

为什么需要 IDataObject 的备份?

如果在所有情况下都可行,它看起来像这样

备份

// expiremental list of formats to exclude. Doesn't cover all possible cases but most of it.
private static readonly string[] clipboardMetaFormats = { "application/x-moz-nativeimage", "FileContents", "EnhancedMetafile", "System.Drawing.Imaging.Metafile", "MetaFilePict", "Object Descriptor", "ObjectLink", "Link Source Descriptor", "Link Source", "Embed Source", "Hyperlink" };

private DataObject ReadClipboard()
{
    DataObject result = new DataObject();
    IDataObject dataObject = Clipboard.GetDataObject();
    string[] formats = dataObject.GetFormats()?.Except(clipboardMetaFormats).ToArray() ?? Array.Empty<string>();
    foreach (string format in formats)
    {
        try
        {
            object data = dataObject.GetData(format);
            if (data != null) result.SetData(format, data);
        }
        catch (ExternalException ex)
        { 
            Debug.WriteLine($"Error {ex.ErrorCode}: {ex.Message}");
        }
    }
    return result;
}
DataObject backup = ReadClipboard();

那么您可以将其用作本地数据存储。例如,如果您想更改 Clipboard,请使用更改后的值,例如将其粘贴到某个应用程序中并将之前的数据恢复到 Clipboard.

还原

private void UpdateClipboard(DataObject data)
{
    if (data == null) return;
    try
    {
        Clipboard.SetDataObject(data);
    }
    catch (ExternalException ex)
    {
        Debug.WriteLine($"Error {ex.ErrorCode}: {ex.Message}");
    }
}
UpdateClipboard(backup);

但您的情况很简单 string。你可以这样做:

string text = Clipboard.GetText(TextDataFormat.UnicodeText);
Clipboard.SetText(text, TextDataFormat.UnicodeText);