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

icomxhvb  于 2023-05-19  发布在  Windows
关注(0)|答案(2)|浏览(128)

我开发了一个应用程序谁粘贴内容到剪贴板从它的后台任务。

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中做到这一点。

ehxuflar

ehxuflar1#

我过去曾用这个从后台线程在UI线程上执行……

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

avkwfej42#

根据@Edd的回答完整回答:

using Windows.ApplicationModel.Core;
using Windows.UI.Core;

...

public static void SetClipbordContent(string text) {
    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        DataPackage dataPackage = new DataPackage();
                        dataPackage.RequestedOperation = DataPackageOperation.Copy;
                        dataPackage.SetText(text);
                        Clipboard.SetContent(dataPackage);
                    });
}

相关问题