2010-08-23 59 views
309

如何将字符串(例如“hello”)复制到C#中的系统剪贴板,所以下次按CTRL + V我会得到“hello”?如何在C#中将数据复制到剪贴板

+4

可能重复[如何复制一个字符串的内容剪贴板在C#?](http://stackoverflow.com/questions/899350/how-to-copy-the-contents-of-a-string-to-the-clipboard-in-c) – 2014-08-06 07:10:30

回答

602

你需要一个命名空间声明:

using System.Windows.Forms; 

OR为WPF:

using System.Windows; 

要复制一个确切的字符串(文字在这种情况下):

Clipboard.SetText("Hello, clipboard"); 

要复制文本框的内容:

Clipboard.SetText(txtClipboard.Text); 

See here for an example。 或... Official MSDN documentationHere for WPF

+11

击败我吧! +1剪贴板类在'System.Windows.Forms'中 – 2010-08-23 09:00:32

+0

我添加了命名空间,但是我仍然看不到剪贴板类。也许这是因为我usintg控制台应用程序? – aharon 2010-08-23 09:20:41

+0

是的!坦克! – aharon 2010-08-23 09:25:59

39
Clipboard.SetText("hello"); 

你需要使用System.Windows.FormsSystem.Windows命名空间为。

+0

像http://stackoverflow.com/a/3546026/206730相同的答案 - 也许更好地删除它,恕我直言,新手与SO – Kiquenet 2014-09-09 09:43:23

24

我使用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(); 

学分这篇文章here

但这个作品这个问题的经验只有在本地主机上,不要试试这个服务器,导致它不会工作。 在服务器上我通过使用zeroclipboard。唯一的办法,经过大量的研究。

+0

我在自动硒测试(webdriver)中使用它,它效果很好! – 2017-01-13 09:31:59

+0

@ andrew.fox你尝试过你的服务器 - 客户端模型?因为如果它是2个独立的机器,我想它不应该起作用。 – BMaximus 2017-01-13 09:53:39

+0

Lol no,Selenium在代理机器上打开浏览器窗口。 – 2017-01-13 13:24:47

20

对于控制台项目在一步一步的方式,你必须首先添加System.Windows.Forms参考。下面的步骤在Visual Studio 2013社区工作与.NET 4.5:

  1. 解决方案资源管理,展开您的控制台项目。
  2. 右键单击引用,然后单击添加引用...
  3. 大会组,下框架,选择System.Windows.Forms
  4. Click OK

然后,在你的代码的顶部与他人添加以下using声明:

using System.Windows.Forms; 

然后,添加以下Clipboard任。SetText语句代码:

Clipboard.SetText("hello"); 
// OR 
Clipboard.SetText(helloString); 

最后,添加STAThreadAttributeMain方法如下,以避免System.Threading.ThreadStateException

[STAThreadAttribute] 
static void Main(string[] args) 
{ 
    // ... 
} 
+1

类StackOverflowException立即在.NET Framework系统类库中的STAThreadAttribute之前=) – 2015-12-03 22:22:39

+1

我的英雄,谢谢你添加属性!为我节省了一堆时间。 – Rinktacular 2017-06-20 19:39:56

+0

@Rinktacular非常欢迎=)感谢您的反馈! – 2017-06-22 21:09:31