我怎样才能在C#中复制一个字符串(如"hello")到系统剪贴板,以便下次我按CTRL+V就可以得到"hello"?
你需要一个命名空间声明。
using System.Windows.Forms;
或为WPF。
using System.Windows;
要复制一个精确的字符串(本例中为字面意思)。
Clipboard.SetText("Hello, clipboard");
复制一个文本框的内容。
Clipboard.SetText(txtClipboard.Text);
Clipboard.SetText("hello");
你需要使用 "System.Windows.Forms "或 "System.Windows "命名空间来实现。
我使用WPF C#复制到剪贴板和System.Threading.ThreadStateException
解决这个问题的经验是,我的代码在所有浏览器上都能正常工作。
Thread thread = new Thread(() => Clipboard.SetText("String to be copied to clipboard"));
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
thread.Join();
这个帖子的功劳这里
但这只在localhost上有效,所以不要在服务器上尝试,因为它不会起作用。
在服务器端,我通过使用zeroclipboard
来实现。这是经过大量研究后的唯一方法。
对于console项目来说,按部就班的方式,你必须先添加System.Windows.Forms
引用。
以下步骤在Visual Studio Community 2013与.NET 4.5中工作。
右键单击引用,然后单击添加引用...。
在Assemblies组中,在Framework下,选择System.Windows.Forms
。
1.点击确定。
然后,将下面的 "using "语句与其他语句一起添加到代码的顶部。
using System.Windows.Forms;
然后,在您的代码中添加以下Clipboard
.SetText
语句。
Clipboard.SetText("hello");
// OR
Clipboard.SetText(helloString);
最后,在你的 "Main "方法中添加STAThreadAttribute
,如下所示,以避免出现System.Threading.ThreadStateException
。
[STAThreadAttribute]
static void Main(string[] args)
{
// ...
}