557

How can I copy a string (e.g "hello") to the System Clipboard in C#, so next time I press CTRL+V I'll get "hello"?

SanD
  • 839
  • 1
  • 11
  • 31
aharon
  • 7,393
  • 10
  • 38
  • 49
  • 8
    possible duplicate of [How to copy the contents of a String to the clipboard in C#?](http://stackoverflow.com/questions/899350/how-to-copy-the-contents-of-a-string-to-the-clipboard-in-c) – Ondrej Janacek Aug 06 '14 at 07:10

10 Answers10

961

There are two classes that lives in different assemblies and different namespaces.

  • WinForms: use following namespace declaration, make sure Main is marked with [STAThread] attribute:

    using System.Windows.Forms;
    
  • WPF: use following namespace declaration

    using System.Windows;
    
  • console: add reference to System.Windows.Forms, use following namespace declaration, make sure Main is marked with [STAThread] attribute. Step-by-step guide in another answer

    using System.Windows.Forms;
    

To copy an exact string (literal in this case):

Clipboard.SetText("Hello, clipboard");

To copy the contents of a textbox either use TextBox.Copy() or get text first and then set clipboard value:

Clipboard.SetText(txtClipboard.Text);

See here for an example. Or... Official MSDN documentation or Here for WPF.


Remarks:

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Kieren Johnstone
  • 41,277
  • 16
  • 94
  • 144
  • @KierenJohnstone Is it possible to access clipboard contents using key-value pairs? – Honinbo Shusaku Jan 13 '16 at 03:04
  • @Abdul - I'm not sure what you mean. Clipboard contents can be text, files, images, any sort of custom data. The concept of kv-pairs doesn't seem to be anything to do with the clipboard idea? – Kieren Johnstone Jan 14 '16 at 10:31
  • @KierenJohnstone what I'm attempting to make is something there an user can store multiple things in the clipboard. Those things would be accessed by a key. It's similar to HTML5 Local storage. Or is something like that not possible due to the nature of the clipboard? – Honinbo Shusaku Jan 21 '16 at 16:02
  • If are you getting error with ASP.NET, try using into a new thread: var thread = new Thread(param => { Clipboard.SetText(txtName.Text); }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); – user3790692 Mar 16 '16 at 16:18
  • Never do this from ASP.NET. It's a server-side technology, meaning you'll be copying to the clipboard on the server. Worst idea ever. – Kieren Johnstone Mar 13 '17 at 12:58
  • 2
    skia.heliou's answer helped me: after adding attribute [STAThreadAttribute], my Clipboard.SetText method start working – viteo Sep 14 '17 at 12:10
  • For .NET Core 3.1 -- `System.Windows.Clipboard` class is available and `Clipboard.SetText` works; but I've tested only on Windows 10. – SNag Nov 13 '20 at 08:18
  • In case anyone needs to do this in uwp https://learn.microsoft.com/en-us/windows/uwp/app-to-app/copy-and-paste – Donald Feb 18 '21 at 19:38
60

For console projects in a step-by-step fashion, you'll have to first add the System.Windows.Forms reference. The following steps work in Visual Studio Community 2013 with .NET 4.5:

  1. In Solution Explorer, expand your console project.
  2. Right-click References, then click Add Reference...
  3. In the Assemblies group, under Framework, select System.Windows.Forms.
  4. Click OK.

Then, add the following using statement in with the others at the top of your code:

using System.Windows.Forms;

Then, add either of the following Clipboard.SetText statements to your code:

Clipboard.SetText("hello");
// OR
Clipboard.SetText(helloString);

And lastly, add STAThreadAttribute to your Main method as follows, to avoid a System.Threading.ThreadStateException:

[STAThreadAttribute]
static void Main(string[] args)
{
  // ...
}
nikodaemus
  • 1,918
  • 3
  • 21
  • 32
  • 1
    The class `StackOverflowException` immediately precedes `STAThreadAttribute` in the .NET Framework System Class Library =) – nikodaemus Dec 03 '15 at 22:22
50

My Experience with this issue using WPF C# coping to clipboard and System.Threading.ThreadStateException is here with my code that worked correctly with all browsers:

Thread thread = new Thread(() => Clipboard.SetText("String to be copied to clipboard"));
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start(); 
thread.Join();

credits to this post here

But this works only on localhost, so don't try this on a server, as it's not going to work.

On server-side, I did it by using zeroclipboard. The only way, after a lot of research.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
BMaximus
  • 1,062
  • 1
  • 11
  • 19
43
Clipboard.SetText("hello");

You'll need to use the System.Windows.Forms or System.Windows namespaces for that.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Bradley Smith
  • 13,353
  • 4
  • 44
  • 57
8

Clip.exe is an executable in Windows to set the clipboard. Note that this does not work for other operating systems other than Windows, which still sucks.

        /// <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;
        }
QB kyu
  • 91
  • 2
  • 5
3

If you don't want to set the thread as STAThread, use Clipboard.SetDataObject(object sthhere):

Clipboard.SetDataObject("Yay! No more STA thread!");
Ujhhgtg
  • 31
  • 3
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 12 '22 at 06:11
  • It works, but not without STAThread. My C# WinForms program defaulted to having STAThread on Main() (in Program.cs). So it might just be a difference between old versions of VS and VS2019. Removing STAThread from Main() causes exceptions when I try to copy. – MichaelS Feb 25 '22 at 02:03
  • I also get an exception without STAThread and the clipboard will be emptied (instead of having that string in it). The answer seems to be incorrect, not badly supported. – Anders Lindén Dec 04 '22 at 05:19
2

This works on .net core, no need to reference System.Windows.Forms

using Windows.ApplicationModel.DataTransfer;

DataPackage package = new DataPackage();
package.SetText("text to copy");
Clipboard.SetContent(package);

It works cross-platform. On windows, you can press windows + V to view your clipboard history

Luke Vanzweden
  • 466
  • 3
  • 15
1

On ASP.net web forms use in the @page AspCompat="true", add the system.windows.forms to you project. At your web.config add:

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" />
  </appSettings>

Then you can use:

Clipboard.SetText(CreateDescription());
Dharman
  • 30,962
  • 25
  • 85
  • 135
0

If you don't want too or cannot use System.Windows.Forms you can use the Windows native api: user32 and the clipboard functions GetClipboardData and SetClipboardDat (pinvoke)

A .NET 6 wrapper library can be found here https://github.com/MrM40/WitWinClipboard/tree/main

MrCalvin
  • 1,675
  • 1
  • 19
  • 27
0

For the modern cross-platform .NET, you'll need to use the MAUI version. The short answer is await Clipboard.Default.SetTextAsync("This text was highlighted in the UI."); and Microsoft.Maui.Essentials.dll should be referenced. The long answer is covered in this article.

Siavash Mortazavi
  • 1,382
  • 1
  • 14
  • 18