我怎么能复制一个字符串(例如“hello”)到系统剪贴板在c#,所以下次我按CTRL+V我会得到“hello”?
当前回答
如果你不想或者不能使用System.Windows.Forms,你可以使用Windows本地api: user32和剪贴板函数GetClipboardData和SetClipboardDat (pinvoke)
.NET 6包装器库可以在这里找到https://github.com/MrM40/WitWinClipboard/tree/main
其他回答
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;
}
这在。net core上工作,不需要引用System.Windows.Forms
using Windows.ApplicationModel.DataTransfer;
DataPackage package = new DataPackage();
package.SetText("text to copy");
Clipboard.SetContent(package);
它是跨平台的。在windows上,您可以按windows + V查看剪贴板历史记录
在ASP.net web表单中使用@page AspCompat="true",将system.windows.forms添加到你的项目中。 在你的网上。配置添加:
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" />
</appSettings>
然后你可以使用:
Clipboard.SetText(CreateDescription());
对于控制台项目,您必须首先添加System.Windows.Forms引用。以下步骤在Visual Studio Community 2013和。net 4.5中工作:
在“解决方案资源管理器”中展开控制台项目。 右键单击引用,然后单击添加引用… 在“程序集”组中,在“框架”下,选择System.Windows.Forms。 单击OK。
然后,将下面的using语句添加到代码顶部的其他语句中:
using System.Windows.Forms;
然后,添加下列剪贴板之一。SetText语句到你的代码:
Clipboard.SetText("hello");
// OR
Clipboard.SetText(helloString);
最后,将STAThreadAttribute添加到Main方法中,以避免System.Threading.ThreadStateException:
[STAThreadAttribute]
static void Main(string[] args)
{
// ...
}
如果你不想或者不能使用System.Windows.Forms,你可以使用Windows本地api: user32和剪贴板函数GetClipboardData和SetClipboardDat (pinvoke)
.NET 6包装器库可以在这里找到https://github.com/MrM40/WitWinClipboard/tree/main
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和