我试过这段代码:
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)
Tho*_*and 14
把[STAThread]你上面的主要方法:
[STAThread]
static void Main()
{
}
Run Code Online (Sandbox Code Playgroud)
小智 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)