3

To copy something to the clipboard in Windows (at least in .NET as far as I know) it has to be done on a separate thread that is in STA Mode. One example I have used is this.

Thread thread = new Thread(() => Clipboard.SetText(s.Trim()));
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
thread.Join();

Why do I have to do all of that instead of being able to just call:

Clipboard.SetText("text")
2
  • 1
    The joys of COM... Dec 10, 2015 at 15:28
  • 1
    A better question is why .Net doesn't have such a method which delegates to an internal sta thread
    – Bwmat
    Dec 10, 2015 at 15:46

1 Answer 1

1

In a word, legacy.

In the article Why is STAThread required?, we're told:

When the STAThreadAttribute is applied, it changes the apartment state of the current thread to be single threaded. Without getting into a huge discussion about COM and threading, this attribute ensures the communication mechanism between the current thread and other threads that may want to talk to it via COM. When you're using Windows Forms, depending on the feature you're using, it may be using COM interop in order to communicate with operating system components. Good examples of this are the Clipboard and the File Dialogs.

Said another way, communication with operating system components like the Clipboard are handled through COM and that requires changing the apartment state of the thread by using an STA thread.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.