How to copy data to clipboard in C#

C#Clipboard

C# Problem Overview


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"?

C# Solutions


Solution 1 - C#

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:

Solution 2 - C#

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)
{
  // ...
}

Solution 3 - C#

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.

Solution 4 - C#

Clipboard.SetText("hello");

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

Solution 5 - C#

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

Solution 6 - C#

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

Clipboard.SetDataObject("Yay! No more STA thread!");

Solution 7 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaharonView Question on Stackoverflow
Solution 1 - C#Kieren JohnstoneView Answer on Stackoverflow
Solution 2 - C#skia.heliouView Answer on Stackoverflow
Solution 3 - C#BMaximusView Answer on Stackoverflow
Solution 4 - C#Bradley SmithView Answer on Stackoverflow
Solution 5 - C#QB kyuView Answer on Stackoverflow
Solution 6 - C#UjhhgtgView Answer on Stackoverflow
Solution 7 - C#Walter KohlView Answer on Stackoverflow