Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Clipboard content using a Background Task [Windows 10] [UWP]

Tags:

c#

uwp

I'm working on a Universal Windows 10 App. At the moment I have a background task that gets triggered once the user receives a notification. The purpose of this BG task is to copy the content of the notification. The problem is that the Clipboard.setcontent method appears to be single threaded as opposed to the multi threaded BG task. I have tried using the corewindow dispatcher but that didn't work, I also tried using tasks. Could someone point me out to the solution please?

E.g. the following code in a background task throws the exception:

Activating a single-threaded class from MTA is not supported (Exception from HRESULT: 0x8000001D).

Code:

var dataPackage = new DataPackage { RequestedOperation = DataPackageOperation.Copy };
dataPackage.SetText("Hello World!");
Clipboard.SetContent(dataPackage);
like image 430
Saeed Sefrini Avatar asked Sep 28 '22 01:09

Saeed Sefrini


1 Answers

Save the content somewhere and assign the string to the Clipboard while the app is about to resume.

await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
    var dataPackage = new DataPackage { RequestedOperation = DataPackageOperation.Copy };
    dataPackage.SetText("Hello World!");
    Clipboard.SetContent(dataPackage);

    getText();
});

private async void getText()
{
    string t = await Clipboard.GetContent().GetTextAsync();
}
like image 160
James He Avatar answered Oct 03 '22 21:10

James He