[英]C# Copy to Clipboard
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.我想在 C# 中制作一个控制台应用程序,用户将在其中输入一些内容,比如说“Dave”,然后它会输出“Name:Dave”并将“Name:Dave”复制到用户剪贴板。 So is there a way to have the "Name: " + Console.ReadLine();那么有没有办法让“名称:”+ Console.ReadLine(); copied to the users clipboard automatically?自动复制到用户剪贴板?
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();
}
}
}
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 应用程序中也有很有价值的用途。
1: You need to add a reference to System.Windows.Forms
as follows: 1:需要添加对System.Windows.Forms
的引用如下:
Right-click your project in Solution Explorer
and select Add reference
... and then find System.Windows.Forms
and add it.在Solution Explorer
右键单击您的项目并选择Add reference
...,然后找到System.Windows.Forms
并添加它。 ( look at this answer ) (看看这个答案)
2: Then you can add System.Windows.Forms
to your code using the line below and make sure you place it correctly where it should be with other using
(s): 2:然后您可以使用下面的行将System.Windows.Forms
添加到您的代码中,并确保将其正确放置在其他using
(s)的位置:
using System.Windows.Forms;
3: Add [STAThread]
on the top of your Main
function, so it should be like this: 3:在你的Main
函数顶部添加[STAThread]
,应该是这样的:
[STAThread]
static void Main(string[] args)
{
....
}
4: Use Clipboard
as you like, for example: 4: Clipboard
使用Clipboard
,例如:
Clipboard.SetText("Sample Text");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.