user2923446
user2923446

Reputation: 409

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. So is there a way to have the "Name: " + Console.ReadLine(); copied to the users clipboard automatically?

Upvotes: 29

Views: 71888

Answers (3)

Khalil Youssefi
Khalil Youssefi

Reputation: 414

1: You need to add a reference to System.Windows.Forms as follows:

Right-click your project in Solution Explorer and select Add reference... and then find System.Windows.Forms and add it. (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):

using System.Windows.Forms;

3: Add [STAThread] on the top of your Main function, so it should be like this:

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

4: Use Clipboard as you like, for example:

Clipboard.SetText("Sample Text");

Upvotes: 6

Alex
Alex

Reputation: 38519

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();
        }
    }
}

Upvotes: 53

Alex Walker
Alex Walker

Reputation: 2356

Use

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

where message is the string to be copied.

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.

Upvotes: 21

Related Questions