Kieran Quinn
Kieran Quinn

Reputation: 1115

Set string value from clipboard contents C#

I'm writing a small app that should display the number of characters in the current string from the clipboard. So for example, someone highlights a line of text and hits copy, then runs my app. I want it to display the number of characters in the string. Should be simple, but I keep getting Zero returned. There are related threads but none answer my question. Here is what I have so far (Its a console app btw.):

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace BuildandRun
{
    class Program
    {
        static void Main(string[] args)
        {
            string data = Clipboard.GetText();
            Console.WriteLine(data);
            int dataLength = data.Length;
            Console.WriteLine(dataLength + " Characters.");

            Console.ReadLine();
        }
    }
}

Upvotes: 0

Views: 365

Answers (2)

Matthew Watson
Matthew Watson

Reputation: 109567

The Clipboard only works for Single Threaded Apartment threads.

Therefore the answer is to add the following to Main():

[STAThread]
static void Main(string[] args)
{
    ...

Or workaround like this:

public string GetClipboardText()
{
    string result = "";

    Thread thread = new Thread(() => result = Clipboard.GetText());
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    thread.Join();

    return result;
}

Upvotes: 0

Alex Costa
Alex Costa

Reputation: 306

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.

Just change your code to:

[STAThreadAttribute]
static void Main( string[] args )

Upvotes: 1

Related Questions