25

我想在 C# 中制作一个控制台应用程序,用户将在其中输入一些内容,比如“Dave”,然后它会输出“Name: Dave”并将“Name: Dave”复制到用户剪贴板。那么有没有办法让“名称:” + Console.ReadLine(); 自动复制到用户剪贴板?

4

3 回答 3

47

您需要引用一个命名空间:

using System.Windows.Forms;

然后你可以使用:

Clipboard.SetText("Whatever you like");

编辑

这是一个适合我的复制和粘贴解决方案

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();
        }
    }
}
于 2013-10-31T13:33:19.673 回答
18

利用

System.Windows.Forms.Clipboard.SetText(message)

其中 message 是要复制的字符串。

尽管 System.Windows.Forms 命名空间是为 Windows 窗体设计的,但其 API 中的许多方法即使在控制台/其他非 Winforms 应用程序中也具有重要用途。

于 2013-10-31T13:33:13.017 回答
3

1:需要添加引用System.Windows.Forms如下:

右键单击您的项目Solution Explorer并选择Add reference...,然后找到System.Windows.Forms并添加它。(看看这个答案

2:然后您可以System.Windows.Forms使用下面的行添加到您的代码中,并确保将其正确放置在与其他using(s)应位于的位置:

using System.Windows.Forms;

3:[STAThread]在你的函数顶部添加Main,所以它应该是这样的:

[STAThread]
static void Main(string[] args)
{
      ....
}
    

4:随意使用Clipboard,例如:

Clipboard.SetText("Sample Text");
于 2021-03-10T11:16:25.800 回答