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

aha*_*ron 409 c# clipboard

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

Kie*_*one 764

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

using System.Windows.Forms;
Run Code Online (Sandbox Code Playgroud)

或WPF:

using System.Windows;
Run Code Online (Sandbox Code Playgroud)

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

Clipboard.SetText("Hello, clipboard");
Run Code Online (Sandbox Code Playgroud)

要复制文本框的内容:

Clipboard.SetText(txtClipboard.Text);
Run Code Online (Sandbox Code Playgroud)

请看这里的例子.或者...... 官方MSDN文档此处为WPF.

  • 是的,WinForms和WPF ......有机会在控制台应用程序中执行此操作吗? (5认同)
  • skia.heliou 的回答对我有帮助:添加属性 [STAThreadAttribute] 后,我的 Clipboard.SetText 方法开始工作 (2认同)

Bra*_*ith 42

Clipboard.SetText("hello");
Run Code Online (Sandbox Code Playgroud)

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


BMa*_*mus 41

我使用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();
Run Code Online (Sandbox Code Playgroud)

学分这篇文章在这里

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

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


ski*_*iou 41

对于逐步进行控制台项目,您必须先添加System.Windows.Forms引用.以下步骤适用于Visual Studio Community 2013 with .NET 4.5:

  1. Solution Explorer中,展开控制台项目.
  2. 右键单击" 引用",然后单击" 添加引用"...
  3. 大会组,下框架,选择System.Windows.Forms.
  4. 单击确定.

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

using System.Windows.Forms;
Run Code Online (Sandbox Code Playgroud)

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

Clipboard.SetText("hello");
// OR
Clipboard.SetText(helloString);
Run Code Online (Sandbox Code Playgroud)

最后,添加STAThreadAttribute到您的Main方法如下,以避免System.Threading.ThreadStateException:

[STAThreadAttribute]
static void Main(string[] args)
{
  // ...
}
Run Code Online (Sandbox Code Playgroud)


QB *_*kyu 9

Clip.exe 是 Windows 中用于设置剪贴板的可执行文件。请注意,这不适用于Windows 以外的其他操作系统,Windows 仍然很糟糕。

        /// <summary>
        /// Sets clipboard to value.
        /// </summary>
        /// <param name="value">String to set the clipboard to.</param>
        public static void SetClipboard(string value)
        {
            if (value == null)
                throw new ArgumentNullException("Attempt to set clipboard with null");

            Process clipboardExecutable = new Process(); 
            clipboardExecutable.StartInfo = new ProcessStartInfo // Creates the process
            {
                RedirectStandardInput = true,
                FileName = @"clip", 
            };
            clipboardExecutable.Start();

            clipboardExecutable.StandardInput.Write(value); // CLIP uses STDIN as input.
            // When we are done writing all the string, close it so clip doesn't wait and get stuck
            clipboardExecutable.StandardInput.Close(); 

            return;
        }
Run Code Online (Sandbox Code Playgroud)