How do I copy the contents of a String to the clipboard in C#?

C#.NetClipboard

C# Problem Overview


If I have some text in a String, how can I copy that to the clipboard so that the user can paste it into another window (for example, from my application to Notepad)?

C# Solutions


Solution 1 - C#

You can use System.Windows.Forms.Clipboard.SetText(...).

Solution 2 - C#

Solution 3 - C#

I wish calling SetText were that easy but there are quite a few gotchas that you have to deal with. You have to make sure that the thread you are calling it on is running in the STA. It can sometimes fail with an access denied error then work seconds later without problem - something to do with the COM timing issues in the clipboard. And if your application is accessed over Remote Desktop access to the clipboard is sketchy. We use a centralized method to handle all theses scenarios instead of calling SetText directly.

@Stecy: Here's our centralized code:

The StaHelper class simply executes some arbitrary code on a thread in the Single Thread Apartment (STA) - required by the clipboard.

abstract class StaHelper
{
	readonly ManualResetEvent _complete = new ManualResetEvent( false );	

	public void Go()
	{
		var thread = new Thread( new ThreadStart( DoWork ) )
		{
			IsBackground = true,
		}
		thread.SetApartmentState( ApartmentState.STA );
		thread.Start();
	}

	// Thread entry method
	private void DoWork()
	{
		try
		{
			_complete.Reset();
			Work();
		}
		catch( Exception ex )
		{
			if( DontRetryWorkOnFailed )
				throw;
			else
			{
				try
				{
					Thread.Sleep( 1000 );
					Work();
				}
				catch
				{
					// ex from first exception
					LogAndShowMessage( ex );
				}
			}
		}
		finally
		{
			_complete.Set();
		}
	}

	public bool DontRetryWorkOnFailed{ get; set; }

	// Implemented in base class to do actual work.
	protected abstract void Work();
}

Then we have a specific class for setting text on the clipboard. Creating a DataObject manually is required in some edge cases on some versions of Windows/.NET. I don't recall the exact scenarios now and it may not be required in .NET 3.5.

class SetClipboardHelper : StaHelper
{
	readonly string _format;
	readonly object _data;

	public SetClipboardHelper( string format, object data )
	{
		_format = format;
		_data = data;
	}

	protected override void Work()
	{
		var obj = new System.Windows.Forms.DataObject(
			_format,
			_data
		);

		Clipboard.SetDataObject( obj, true );
	}
}

Usage looks like this:

new SetClipboardHelper( DataFormats.Text, "See, I'm on the clipboard" ).Go();

Solution 4 - C#

WPF: System.Windows.Clipboard (PresentationCore.dll)

Winforms: System.Windows.Forms.Clipboard

Both have a static SetText method.

Solution 5 - C#

This works for me:

You want to do:

System.Windows.Forms.Clipboard.SetText("String to be copied to Clipboard");

But it causes an error saying it must be in a single thread of ApartmentState.STA.

So let's make it run in such a thread. The code for it:

public void somethingToRunInThread()
{
    System.Windows.Forms.Clipboard.SetText("String to be copied to Clipboard");
}

protected void copy_to_clipboard()
{
    Thread clipboardThread = new Thread(somethingToRunInThread);
    clipboardThread.SetApartmentState(ApartmentState.STA);
    clipboardThread.IsBackground = false;
    clipboardThread.Start();
}

After calling copy_to_clipboard(), the string is copied into the clipboard, so you can Paste or Ctrl + V and get back the string as String to be copied to the clipboard.

Solution 6 - C#

Using the solution showed in this question, System.Windows.Forms.Clipboard.SetText(...), results in the exception:

> Current thread must be set to single thread apartment (STA) mode before OLE calls can be made

To prevent this, you can add the attribute:

[STAThread]

to

static void Main(string[] args)

Solution 7 - C#

In Windows Forms, if your string is in a textbox, you can easily use this:

textBoxcsharp.SelectAll();
textBoxcsharp.Copy();
textBoxcsharp.DeselectAll();

Solution 8 - C#

Use try-catch, even if it has an error it will still copy.

Try
   Clipboard.SetText("copy me to clipboard")
Catch ex As Exception

End Try

If you use a message box to capture the exception, it will show you error, but the value is still copied to clipboard.

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
QuestionElieView Question on Stackoverflow
Solution 1 - C#ravuyaView Answer on Stackoverflow
Solution 2 - C#Jeff MoserView Answer on Stackoverflow
Solution 3 - C#Paul AlexanderView Answer on Stackoverflow
Solution 4 - C#bsneezeView Answer on Stackoverflow
Solution 5 - C#benli1212View Answer on Stackoverflow
Solution 6 - C#LeroyView Answer on Stackoverflow
Solution 7 - C#Magnetic_dudView Answer on Stackoverflow
Solution 8 - C#Abu FaisalView Answer on Stackoverflow