从剪贴板获取内容时出现 "The application called an interface that was marshalled for a different thread" 错误

Get "The application called an interface that was marshalled for a different thread" error while getting content from Clipboard

目标:使用 C++/WinRT APIs 从剪贴板获取内容。

问题:

因为我只是在测试这个 API,所以我尝试在剪贴板的异步文本 getter 上使用阻塞 get() 方法编写一个简单的控制台应用程序。但是,我在调试时收到 "The application called an interface that was marshalled for a different thread" 错误。我还尝试将单元初始化为单线程单元 (STA),但我猜这是不允许的,因为抛出了另一个断言错误 (!is_sta())。现在我只是想知道为什么在调用 get 时会抛出此错误,以及如何在我的控制台应用程序中从剪贴板检索内容。 (我看到一些示例(主要是 GUI 应用程序)正在使用我不熟悉的协程。)

代码:

using namespace winrt::Windows::ApplicationModel::DataTransfer;

int main()
{
    init_apartment();

    hstring text{ Clipboard::GetContent().GetTextAsync().get() };
    std::wcout << text.c_str() << std::endl;
}

错误信息:

Exception thrown at 0x7659ACC2 (KernelBase.dll) in test-clipboard.exe: WinRT originate error - 0x8001010E : 'The application called an interface that was marshalled for a different thread.'.
'test-clipboard.exe' (Win32): Loaded 'C:\Windows\SysWOW64\bcrypt.dll'. 
Exception thrown at 0x7659ACC2 in test-clipboard.exe: Microsoft C++ exception: winrt::hresult_wrong_thread at memory location 0x010FF818.
Unhandled exception at 0x7659ACC2 in test-clipboard.exe: Microsoft C++ exception: winrt::hresult_wrong_thread at memory location 0x010FF818.

衷心感谢您的帮助。谢谢。

WinRT 剪贴板 API 只能从具有 CoreWindow 的 UI 线程调用。请参阅注释 In the documentation。您可以在控制台应用程序中使用常规的 Win32 剪贴板 API。