繁体   English   中英

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

[英]How to copy data to clipboard in C#

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

有两个类存在于不同的程序集和不同的命名空间中。

  • WinForms:使用以下命名空间声明,确保Main标记有[STAThread]属性:

     using System.Windows.Forms;
  • WPF:使用以下命名空间声明

    using System.Windows;
  • 控制台:添加对System.Windows.Forms的引用,使用以下命名空间声明,确保Main标记有[STAThread]属性。 另一个答案中的分步指南

    using System.Windows.Forms;

要复制一个精确的字符串(在这种情况下是字面量):

Clipboard.SetText("Hello, clipboard");

要复制文本框的内容,请使用TextBox.Copy()或先获取文本,然后设置剪贴板值:

Clipboard.SetText(txtClipboard.Text);

有关示例,请参见此处 或者......官方 MSDN 文档WPF 的 Here


评论:

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

  1. 解决方案资源管理器中,展开您的控制台项目。
  2. 右键单击References ,然后单击Add Reference...
  3. Assemblies组中的Framework下,选择System.Windows.Forms
  4. 单击确定

然后,将以下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)
{
  // ...
}

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

这篇文章的学分在这里

但这仅适用于本地主机,所以不要在服务器上尝试,因为它不起作用。

在服务器端,我使用zeroclipboard来完成。 唯一的办法,经过大量研究。

Clipboard.SetText("hello");

为此,您需要使用System.Windows.FormsSystem.Windows命名空间。

Clip.exe 是 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;
        }

如果您不想将线程设置为 STAThread,请使用Clipboard.SetDataObject(object sthhere)

Clipboard.SetDataObject("Yay! No more STA thread!");

在@page AspCompat="true" 中使用的 ASP.net Web 表单上,将 system.windows.forms 添加到您的项目中。 在您的 web.config 添加:

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" />
  </appSettings>

然后你可以使用:

Clipboard.SetText(CreateDescription());

这适用于 .net 核心,无需参考System.Windows.Forms

using Windows.ApplicationModel.DataTransfer;

DataPackage package = new DataPackage();
package.SetText("text to copy");
Clipboard.SetContent(package);

它可以跨平台工作。 在 Windows 上,您可以按windows + V查看剪贴板历史记录

或者您可以调用 Windows 本机 user32 剪贴板函数GetClipboardDataSetClipboardDat (pinvoke)

可以在此处找到 .NET 6 包装库https://github.com/MrM40/WitWinClipboard/tree/main

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM