我怎么能复制一个字符串(例如“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
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和