Search code examples
c#clipboard

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


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

Clipboard.SetText("Test!");

And I get this error:

Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it.

How can I fix it?


Solution

  • 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.