How to copy data to clipboard in C#

By FoxLearn 12/5/2024 11:16:51 AM   146
To copy data to the clipboard in C#, you can use the Clipboard class from the System.Windows.Forms or System.Windows namespaces.

In C#, working with the clipboard is straightforward, thanks to the Clipboard class available in the .NET framework.

For example, Using System.Windows.Forms (Windows Forms Application)

using System.Windows.Forms;

Clipboard.SetText(text);

The System.Windows.Forms.Clipboard class provides methods for interacting with the clipboard in a Windows Forms application. To use it, add a reference to the System.Windows.Forms namespace.

For example, Using System.Windows (WPF Application)

using System.Windows;

Clipboard.SetText(text);

If you’re working with a WPF application, you’ll use the System.Windows.Clipboard class.

For WPF applications, ensure the PresentationCore assembly is referenced.

Clipboard operations in .NET require the application to run in a single-threaded apartment (STA) mode. If you're working in a console application, add [STAThread] to the Main method.

[STAThread]
static void Main(string[] args)
{
    Clipboard.SetText("Hello, Clipboard!");
}

For a console application, add [STAThread] to the Main method.

To check if the clipboard contains text, you can use

if (Clipboard.ContainsText())
{
    string text = Clipboard.GetText();
}

The clipboard supports multiple formats. For instance, you can copy not just plain text but also images, files, and custom data.

For example, Copying Rich Text:

Clipboard.SetText("<b>C# Programming</b>", TextDataFormat.Html);

For example, Copying Images:

Bitmap bitmap = new Bitmap("example.png");
Clipboard.SetImage(bitmap);

For example, Copying Files:

string[] files = { @"C:\example1.txt", @"C:\example2.txt" };
Clipboard.SetFileDropList(new System.Collections.Specialized.StringCollection() { files });

Copying data to the clipboard in C# is simple and versatile, with support for multiple data formats and platform compatibility. Depending on your application type, you can use either the Clipboard class from System.Windows.Forms or System.Windows.