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

后端 未结 3 727
鱼传尺愫
鱼传尺愫 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:14

    Make sure thread that runs the code is marked with [STAThread] attribute. For WinForm and console based apps it is generally Main method

    Put [STAThread] above your main method:

    [STAThread]
    static void Main()
    {
    }
    

    For WinForms it is usually in generated Main.cs file that you can edit if necessary (it will not be re-generated on changes). For console it's were you define the Main.

    If you can't control the thread (i.e. you are writing a library or main app is locked by some reason) you can instead run code that accesses clipboard on specially configured thread (.SetApartmentState(ApartmentState.STA)) as shown in another answer.

提交回复
热议问题