Set Clipboard content in Cortana background task

1

I am trying to add content to the Clipboard in a background task but I can't get it to work. here is my Code:

var dataPackage = new DataPackage { RequestedOperation = DataPackageOperation.Copy };
dataPackage.SetText("EUREKA!");
Clipboard.Flush();
Clipboard.SetContent(dataPackage);

I get the error Message:

Activating a single-threaded class from MTA is not supported (Exception from HRESULT: 0x8000001D) System.Exception {System.Runtime.InteropServices.COMException}

I found a similar question with a Notification and not Cortana but the proposed solution:

private async Task CopyToClipboard(string strText)
{
    CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
    await dispatcher.RunAsync(CoreDispatcherPriority.Normal,
            () =>
            {
                var dataPackage = new DataPackage { RequestedOperation = DataPackageOperation.Copy };
                dataPackage.SetText("EUREKA!");
                Clipboard.SetContent(dataPackage);

                getText();
            });

}
private async void getText()
{
    string t = await Clipboard.GetContent().GetTextAsync();
}

Throws a System.NullReferenceException

c#
uwp
cortana
asked on Stack Overflow Oct 6, 2015 by DevEnitly • edited May 23, 2017 by Community

1 Answer

3

The first error message is very clear. The clipboard expect STA thread. And for the app developed by c# (your case) or c++, the background tasks are hosted in an in-proc DLL (loaded by the app or the dedicated BackgroundtaskHost.exe) that is in MTA.

There are two scenarios:

  1. Forefront app is in running mode: The coredispatcher can be used to ask the UI STA thread to perform the action.

  2. Forefront app is suspended or terminated: The background task (when app written in c# and c++) always runs in MTA mode and the UI STA thread doesn't exist, so we cannot use Clipboard in background task for this scenario if the class doesn't support the activation from MTA.

So remember this:

The only reliable way for the background task to share state is to use persistent storage, such as ApplicationData, or files.

answered on Stack Overflow Oct 6, 2015 by Alan Yao - MSFT

User contributions licensed under CC BY-SA 3.0