How to copy data to clipboard in C#

aharon picture aharon · Aug 23, 2010 · Viewed 377k times · Source

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

Answer

Kieren Johnstone picture Kieren Johnstone · Aug 23, 2010

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: