尝试将字符串复制到剪贴板时出错

use*_*701 16 c# clipboard

我试过这段代码:

Clipboard.SetText("Test!");
Run Code Online (Sandbox Code Playgroud)

我收到这个错误:

在进行OLE调用之前,必须将当前线程设置为单线程单元(STA)模式.确保您的Main功能已STAThreadAttribute在其上标记.

我该如何解决?

It'*_*ie. 37

您需要特别调用该方法,因为它使用了一些遗留代码.试试这个:

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
Run Code Online (Sandbox Code Playgroud)

  • 不关心其他任何事情,但它解决了我的问题。 (2认同)

Tho*_*and 14

[STAThread]你上面的主要方法:

[STAThread]
static void Main()
{
}
Run Code Online (Sandbox Code Playgroud)

  • @new 怎么样?它在`Main.cs` 文件中定义...编辑它非常简单。main 方法与您是否使用 WinForms 无关。请注意,新项目从一开始就正确设置了属性。 (2认同)

小智 9

您只能从 STAThread 访问剪贴板。

解决这个问题的最快方法是放在[STAThread]你的Main()方法之上,但是如果由于某种原因你不能这样做,你可以使用一个单独的类来创建一个 STAThread 设置/获取字符串值给你。

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;
    }
}
Run Code Online (Sandbox Code Playgroud)