C# 复制到剪贴板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19707885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Copy to Clipboard
提问by user2923446
I'd like to make a console application in C#, where the user will type something, let's say "Dave" and then it'll output "Name: Dave" and copy the "Name: Dave" to the users clipboard. So is there a way to have the "Name: " + Console.ReadLine(); copied to the users clipboard automatically?
我想在 C# 中制作一个控制台应用程序,用户将在其中输入一些内容,比如说“Dave”,然后它会输出“Name:Dave”并将“Name:Dave”复制到用户剪贴板。那么有没有办法让“名称:”+ Console.ReadLine(); 自动复制到用户剪贴板?
回答by Alex Walker
Use
用
System.Windows.Forms.Clipboard.SetText(message)
where message is the string to be copied.
其中 message 是要复制的字符串。
Although the System.Windows.Forms namespace was designed for Windows Forms, many methods from its API have valuable uses even in console / other non-Winforms applications.
尽管 System.Windows.Forms 命名空间是为 Windows 窗体设计的,但其 API 中的许多方法即使在控制台/其他非 Winforms 应用程序中也有很有价值的用途。
回答by Alex
You'll need to reference a namespace:
您需要引用一个命名空间:
using System.Windows.Forms;
Then you can use:
然后你可以使用:
Clipboard.SetText("Whatever you like");
EDIT
编辑
Here's a copy and paste solution that works for me
这是一个对我有用的复制和粘贴解决方案
using System;
using System.Windows.Forms;
namespace ConsoleApplication1
{
class Program
{
[STAThread]
private static void Main(string[] args)
{
Console.WriteLine("Say something and it will be copied to the clipboard");
var something = Console.ReadLine();
Clipboard.SetText(something);
Console.Read();
}
}
}