When attempting to call a single-threaded apartment (STA) function from the "wrong" thread (e.g., Clipboard::SetContent(...)
), I see the following message:
Activating a single-threaded class from MTA is not supported.
It's not obvious which functions are STA, so it just seems to jump out from seemingly innocent-looking functions. I couldn't find a simple answer that explains the steps to fix it. The Windows COM documentation is difficult to follow.
How can I reliably identify what is a STA function in order to prevent this error? Isn't there a simple fix?
The problem is that the thread you're currently running on is MTA (multi-threaded apartment), and doesn't support STA calls.
The fix is to dispatch the call from the main/UI thread, which is always STA and therefore supports STA calls.
First, get the thread you want with MainView->CoreWindow
, and then call that thread's dispatcher to invoke whatever it was you wanted to run. For example:
using namespace Windows::UI::Core;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::ApplicationModel::DataTransfer;
CoreWindow^ window = CoreApplication::MainView->CoreWindow;
window->Dispatcher->RunAsync(CoreDispatcherPriority::Normal,
ref new DispatchedHandler
(
[wstringForClipboard]
{
DataPackage^ clipboardInfo = ref new DataPackage;
clipboardInfo->SetText(ref new Platform::String(wstringForClipboard.c_str()));
Clipboard::SetContent(clipboardInfo);
}
)
);