Error while trying to copy string to clipboard

2019-04-19 10:24发布

问题:

I have tried this code:

Clipboard.SetText("Test!");

And I get this error:

Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it.

How can I fix it?

回答1:

Put [STAThread] above your main method:

[STAThread]
static void Main()
{
}


回答2:

You need to call that method specially, because it uses some legacy code. Try this:

Thread thread = new Thread(() => Clipboard.SetText("Test!"));
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start(); 
thread.Join(); //Wait for the thread to end


回答3:

You can only access the clipboard from an STAThread.

The quickest way to solve this is to put [STAThread] on top of your Main() method, but if for whatever reason you cannot do that you can use a separate class that creates an STAThread set/get the string value for to you.

public static class Clipboard
{
    public static void SetText(string p_Text)
    {
        Thread STAThread = new Thread(
            delegate ()
            {
                // Use a fully qualified name for Clipboard otherwise it
                // will end up calling itself.
                System.Windows.Forms.Clipboard.SetText(p_Text);
            });
        STAThread.SetApartmentState(ApartmentState.STA);
        STAThread.Start();
        STAThread.Join();
    }
    public static string GetText()
    {
        string ReturnValue = string.Empty;
        Thread STAThread = new Thread(
            delegate ()
            {
                // Use a fully qualified name for Clipboard otherwise it
                // will end up calling itself.
                ReturnValue = System.Windows.Forms.Clipboard.GetText();
            });
        STAThread.SetApartmentState(ApartmentState.STA);
        STAThread.Start();
        STAThread.Join();

        return ReturnValue;
    }
}


标签: c# clipboard