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

0

Aim: Get content from the clipboard using C++/WinRT APIs.

Problem:

Since I'm just testing this API, I tried to code a simple console app with the blocking get() method on Clipboard's async text getter. However, I'm getting the "The application called an interface that was marshalled for a different thread" error when debugging. I also tried to init apartments as single threaded apartment (STA), but I guess it's not allowed because another assertion error (!is_sta()) is thrown. Now I'm just wondering why this error is thrown when calling get and how to retrieve the content from clipboard in my console app. (I saw some examples (mostly GUI apps) are using coroutines which I'm not familiar with though.)

Code:

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

int main()
{
    init_apartment();

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

Error message:

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.

Sincerely appreciate your help. Thanks.

c++
windows
winapi
clipboard
c++-winrt
asked on Stack Overflow May 2, 2020 by xlinush • edited May 2, 2020 by xlinush

1 Answer

0

The WinRT clipboard APIs can only be called from a UI thread with a CoreWindow. See notes In the documentation. You can just use the regular Win32 clipboard APIs in your console app.

answered on Stack Overflow May 2, 2020 by Peter Torr - MSFT

User contributions licensed under CC BY-SA 3.0