I write a C# Windows Universal App where the user can copy a file into the clipboard. But if the App is closed the clipboard content gets lost. The usability is horrible if the user can lose his clipboard content so easily. Is there a way to make the clipboard content of the App persistent like in any other classic Windows application?
Sample code:
public static void CopyFileToClipboard(StorageFile file) {
DataPackage dp = new DataPackage();
dp.RequestedOperation = DataPackageOperation.Copy;
dp.SetStorageItems(new List<StorageFile>() { file });
Clipboard.SetContent(dp); // not available after app closed
Clipboard.Flush();
}
public static void CopyTextToClipboard(string text) {
DataPackage dp = new DataPackage();
dp.RequestedOperation = DataPackageOperation.Copy;
dp.SetText(text); // available after app closed
Clipboard.SetContent(dp);
Clipboard.Flush();
}
//I have tried to copy the file to the app folder first but it has nothing changed.
public async static void CacheAndCopyFileToClipboard(StorageFile file) {
DataPackage dp = new DataPackage();
dp.RequestedOperation = DataPackageOperation.Copy;
var xfile = await ApplicationData.Current.LocalFolder.CreateFileAsync(file.Name);
await file.CopyAndReplaceAsync(xfile);
dp.SetStorageItems(new List<StorageFile>() { xfile });
Clipboard.SetContent(dp); // not available after app closed
Clipboard.Flush();
}
So the question is how can I put a file to Clipboard so that users can paste it even if the App is closed?
Edit: It seems that is a problem of all Windows Universal Apps for example if you copy a picture in the Windows Photo App you can only paste it while the Photo App is running. I can not imagine that this strange behavior should be the default behavior of Apps. It looks more like a bug because I see no reason for that strange behavior.
Edit2: New example of the problem (thanks to Joe300 for his feedback). It works with strings but not with a StorageFile (even if it is copied to the local app folder first). What is the reason that the Flush() command does not work with files? Ist there something special to consider when files used (permissions, ... )?
You'll need to add a call to Flush
so that the content is available after the app shuts down.
Adds the content to the Clipboard and releases the DataPackage object from the source app. This method allows the content to remain available after the application shuts down.
You should also set the RequestedOperation
:
dp.RequestedOperation = DataPackageOperation.Copy;
try
{
Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(dp);
Clipboard.Flush();
}
catch (Exception ex)
{
// Copying data to Clipboard can potentially fail - for example, if another application is holding Clipboard open
}
Beyond this, there really aren't any other options for manipulating the Clipboard
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With