首页 文章

如何在C#中将数据复制到剪贴板

提问于
浏览
353

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

4 回答

  • 27

    您需要一个名称空间声明:

    using System.Windows.Forms;
    

    或WPF:

    using System.Windows;
    

    要复制精确的字符串(在本例中为文字):

    Clipboard.SetText("Hello, clipboard");
    

    要复制文本框的内容:

    Clipboard.SetText(txtClipboard.Text);
    

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

  • 674
    Clipboard.SetText("hello");
    

    您需要使用 System.Windows.FormsSystem.Windows 名称空间 .

  • 40

    我使用WPF C#coping到剪贴板和 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

    但这只适用于localhost,所以不要在服务器上尝试这个,因为它不会起作用 .

    在服务器端,我使用 zeroclipboard 完成了它 . 经过大量研究后,唯一的出路 .

  • 33

    对于 console 项目,一步一步地,您必须首先添加 System.Windows.Forms 参考 . 以下步骤适用于Visual Studio Community 2013 with .NET 4.5:

    • Solution Explorer 中,展开您的控制台项目 .

    • 右键单击 References ,然后单击 Add Reference...

    • Assemblies 组中,在 Framework 下,选择 System.Windows.Forms .

    • 单击 OK .

    然后,将以下 using 语句添加到代码顶部的其他语句中:

    using System.Windows.Forms;
    

    然后,添加以下任一项Clipboard . SetText对您的代码的陈述:

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

    最后,将STAThreadAttribute添加到 Main 方法中,如下所示,以避免 System.Threading.ThreadStateException

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

相关问题