UWP:从后台任务请求剪贴板访问

时间:2016-05-29 11:26:00

标签: c# .net windows uwp windows-applications

我开发了一个应用程序,它根据后台任务将内容粘贴到剪贴板。

public sealed class ToastBackgroundTask : IBackgroundTask {
    public void Run(IBackgroundTaskInstance taskInstance) {
        //Inside here developer can retrieve and consume the pre-defined 
        //arguments and user inputs;
        var toastArgs = taskInstance.TriggerDetails as ToastNotificationActionTriggerDetail;
        var argument = toastArgs.Argument;
        SetClipbordContent(toastArgs.Argument);
    }
    public static void SetClipbordContent(string text) {
        var dataPackage = new DataPackage();
        dataPackage.SetText(text);
        Clipboard.SetContent(dataPackage);
    }
}

但是当我执行

行时
Clipboard.SetContent(dataPackage);

提出这个例外:

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

在经典.Net Framework中处理此secario的常用解决方法是使用Thread类在STA上下文中执行此部分代码(C# Clipboard.GetText())但我不知道如何在UWP中执行此操作

1 个答案:

答案 0 :(得分:0)

我过去曾使用它在后台线程的UI线程上执行...

await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => {
    // Do something...
}