“Current thread must be set to single thread apartment (STA)” error in copy string to clipboard

后端 未结 3 729
鱼传尺愫
鱼传尺愫 2020-12-18 18:55

I have tried code from How to copy data to clipboard in C#:

Clipboard.SetText(\"Test!\");

And I get this error:

Curr

3条回答
  •  余生分开走
    2020-12-18 19:22

    If you can't control whether thread runs in STA mode or not (i.e. tests, plugin to some other app or just some code that randomly sends that call to run on no-UI thread and you can't use Control.Invoke to send it back to main UI thread) than you can run clipboard access on thread specifically configured to be in STA state which is required for clipboard access (which internally uses OLE that actually requires STA).

    Thread thread = new Thread(() => Clipboard.SetText("Test!"));
    thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
    thread.Start(); 
    thread.Join(); //Wait for the thread to end
    

提交回复
热议问题