-1

My application need to use some COM objects in MTA (COM object will use UI element), so I defined my app as MTA:

[global::System.MTAThreadAttribute]
static void Main(string[] args)
{
    XamlCheckProcessRequirements();

    global::WinRT.ComWrappersSupport.InitializeComWrappers();
    global::Microsoft.UI.Xaml.Application.Start((p) =>
    {
       var context = new global::Microsoft.UI.Dispatching.DispatcherQueueSynchronizationContext(global::Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread());
                
       global::System.Threading.SynchronizationContext.SetSynchronizationContext(context);
                new App();
     });
}

However, after defining it, i cannot do a copy-paste action on any TextBox in app.

When I checked with Clipboard.SetContent(copyData); it throws an exception: Activating a single-threaded class from MTA is not supported

So, How can i solve this problem?

Hoka Biu
  • 27
  • 6
  • I've never used WinUI. But every other .NET UI framework requires that all UI elements run on the same thread. You very likely need to use the Dispatcher to marshal your call to the UI thread before you use something like the Clipboard – Flydog57 Sep 06 '22 at 17:33
  • 2
    It would be better to use Windows standards (GUI App => Winmain, Main thread => STA) and create as many MTA threads as you need. – Simon Mourier Sep 06 '22 at 17:48

1 Answers1

0

You can do it this way. Say your TextBox's name is TextBoxControl.

DataPackage dataPackage = new()
{
    RequestedOperation = DataPackageOperation.Copy
};

_ = this.TextControl.DispatcherQueue.TryEnqueue(() =>
{
    dataPackage.SetText(this.TextControl.Text);
    Clipboard.SetContent(dataPackage);
});
Andrew KeepCoding
  • 7,040
  • 2
  • 14
  • 21