gpt4 book ai didi

c# - "Current thread must be set to single thread apartment (STA)"将字符串复制到剪贴板时出错

转载 作者:可可西里 更新时间:2023-11-01 07:49:03 24 4
gpt4 key购买 nike

我试过来自 How to copy data to clipboard in C# 的代码:

Clipboard.SetText("Test!");

我得到这个错误:

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.

我该如何解决?

最佳答案

如果您无法控制线程是否以 STA 模式运行(即测试、插件到其他应用程序或只是一些随机发送该调用以在无 UI 线程上运行的代码,并且您不能使用 Control.Invoke 将其发送回主 UI 线程)比您可以在专门配置为处于剪贴板访问所需的 STA 状态的线程上运行剪贴板访问(内部使用 OLE这实际上需要 STA)。

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

关于c# - "Current thread must be set to single thread apartment (STA)"将字符串复制到剪贴板时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17762037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com