Sunday, April 3, 2011

C#: Get Data from Clipboard

I write a application read data from clipboard using System.Windows.Froms. Then I discover the method Clipboard.getDataObject() always returns null.

Based on the description from msdn,

The Clipboard class can only be used in threads set to single thread apartment (STA) mode. To use this class, ensure that your Main method is marked with the STAThreadAttribute attribute.

The sample code is shown below:

class Program
    {
        static void Main(string[] args)
        {
            Thread thread = new Thread(new ThreadStart(CopyToClipboard));
            thread.TrySetApartmentState(ApartmentState.STA);
            thread.Start();
        }
        static void CopyToClipboard()
        {
            IDataObject clip = Clipboard.GetDataObject();
            if (clip.GetDataPresent(DataFormats.Text))
            {
                Console.WriteLine("" + clip.GetData(DataFormats.Text));
            }
        }
    }

No comments:

Post a Comment