我怎么能复制一个字符串(例如“hello”)到系统剪贴板在c#,所以下次我按CTRL+V我会得到“hello”?


当前回答

Clipboard.SetText("hello");

您需要使用System. windows . forms或System。Windows命名空间。

其他回答

这在。net core上工作,不需要引用System.Windows.Forms

using Windows.ApplicationModel.DataTransfer;

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

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

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;
        }
Clipboard.SetText("hello");

您需要使用System. windows . forms或System。Windows命名空间。

如果您不想将线程设置为STAThread,请使用Clipboard。SetDataObject sthhere(对象):

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

如果你不想或者不能使用System.Windows.Forms,你可以使用Windows本地api: user32和剪贴板函数GetClipboardData和SetClipboardDat (pinvoke)

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