Tigraine

Daniel Hoelbling-Inzko talks about programming

Gotchas on your way to the Clipboard

We all know that lovely thing nobody can live without: Clipboard.
Have you ever tried to read the clipboard from your C# code?

Your code may have looked like this:

Clipboard.GetDataObject();

Ok, this code works perfectly fine whenever you try it from a normal Windows-Forms Application Template.
Now, go try accessing the Clipboard from within an Console-Application!

Ok, I know you didn't try, that's why I'm writing this anyway.
Clipboard isn't accessible as long as your Main() isn't looking like this:

[STAThread]
        public static void Main()
        {
            
        }

Why? All the magic lies in the STAThread Attribute!


The STAThread Attribute changes the appartment state of the current thread to be single-threaded. This is necessary for some features especially of Windows Forms (where Clipboard resides in). Why?


Mainly because those features are done through COM-Interop and need to be single-threaded.

Great, my whole application relies on MTAThread, now I'm screwed??


No! Thanks to threading you can always fire up a new thread that is using STA.

[MTAThread]
        public static void Main()
        {
            Thread newThread = new Thread(new ThreadStart(StartingPoint));
            newThread.SetApartmentState(ApartmentState.STA);
            newThread.Start();
        }

public static void StartingPoint() { Clipboard.GetDataObject(); }

Voila, now we have a new Thread that can access the Clipboard without having to change the apartment state of our old thread.
Just remember to set the ApartmentState through the SetApartmentState() function before hitting Start()!

You could also just stick the [MTAThread] attribute ontop of your ThreadStart-Method (but that would be too simple wouldn't it?)

So.. be warned, I had an hour of headaches because of this!

My Photography business

Projects

dynamic css for .NET

Archives

more