Tuesday, December 29, 2009

C# Clipboard in Console Application

In C# accessing the Clipboard suppose to be easy, but you'll find out it doesn't work in the normal way.
Here is a small note from MSDN that I missed at first:

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.
So, in a Console application, use this function:

Code:
public static object GetClipboardData()
{
    object ret = null;
    ThreadStart method = delegate()
    {
        System.Windows.Forms.IDataObject dataObject = Clipboard.GetDataObject();
        if (dataObject != null && dataObject.GetDataPresent(DataFormats.Text))
        {
            ret = dataObject.GetData(DataFormats.Text);
        }
    };
    if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
    {
        Thread thread = new Thread(method);
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();
    }
    else
    {
        method();
    }
    return ret;
}

4 comments:

  1. Thanks! This is just what I was looking for.

    ReplyDelete
  2. I think it not good if you recheck with flow step:
    1 - Run you application
    2 - Open excell
    3 - Put cell a1 value : "aaa"
    4 - Copy cell a1(Ctrl-C)
    5 - Open notepad
    6 - Type "bbb"
    7 - Copy "bbb" of notepad (Ctrl-C)
    8 - Comeback excel
    9 - Paste to cell b1 => value of cell b1 is :"aaa" => not good.

    ReplyDelete
  3. @Anonymous
    I couldn't reproduce the bug you are talking about.
    Maybe you misused the function?

    ReplyDelete
  4. If you just put [STAThread] on static void Main everything works just fine...

    ReplyDelete