“Current thread must be set to single thread apartment (STA)” error in copy string to clipboard

后端 未结 3 730
鱼传尺愫
鱼传尺愫 2020-12-18 18:55

I have tried code from How to copy data to clipboard in C#:

Clipboard.SetText(\"Test!\");

And I get this error:

Curr

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-18 19:03

    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;
        }
    }
    

提交回复
热议问题