Set Clipboard content in Cortana background task

北城余情 提交于 2019-12-06 13:51:53

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/32960822/set-clipboard-content-in-cortana-background-task

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!