I want go get value from 'd' IDataObject to 'c' IDataObject in C# but my 'c' possess value from my Clipboard even when i won't click D key. How can I give independent value from one IDataObject to second?
First function:
if (Keyboard.IsKeyDown(Key.D))
{
d = Clipboard.GetDataObject();
c = d; // <-- doesn't work
string dd = d.GetData(DataFormats.Text).ToString(); //content
MessageBox.Show(dd);
}
Second function
if (Keyboard.IsKeyDown(Key.S))
{
string dd = c.GetData(DataFormats.Text).ToString(); //content
MessageBox.Show(dd);
}
Why do you need a backup of IDataObject
?
If it was possible in all cases it would look like this
Backup
// 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();
Then you may use it as local data storage. For example in case you want to change Clipboard
, use the changed value e.g. paste it into some application and the restore the previous data to Clipboard
.
Restore
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);
But in your case that's a simple string
. You may do it this way:
string text = Clipboard.GetText(TextDataFormat.UnicodeText);
Clipboard.SetText(text, TextDataFormat.UnicodeText);