snippetcsharpCritical
How to copy data to clipboard in C#
Viewed 0 times
datacopyhowclipboard
Problem
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"?
Solution
There are two classes that lives in different assemblies and different namespaces.
-
WinForms: use following namespace declaration, make sure
-
WPF: use following namespace declaration
-
console: add reference to
To copy an exact string (literal in this case):
To copy the contents of a textbox either use TextBox.Copy() or get text first and then set clipboard value:
See here for an example.
Or... Official MSDN documentation or Here for WPF.
Remarks:
-
Clipboard is desktop UI concept, trying to set it in server side code like ASP.Net will only set value on the server and has no impact on what user can see in they browser. While linked answer lets one to run Clipboard access code server side with
-
If after following information in this question code still gets an exception see "Current thread must be set to single thread apartment (STA)" error in copy string to clipboard
-
This question/answer covers regular .NET, for .NET Core see - .Net Core - copy to clipboard?
-
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 answerusing 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:
-
Clipboard is desktop UI concept, trying to set it in server side code like ASP.Net will only set value on the server and has no impact on what user can see in they browser. While linked answer lets one to run Clipboard access code server side with
SetApartmentState it is unlikely what you want to achieve.-
If after following information in this question code still gets an exception see "Current thread must be set to single thread apartment (STA)" error in copy string to clipboard
-
This question/answer covers regular .NET, for .NET Core see - .Net Core - copy to clipboard?
Code Snippets
using System.Windows.Forms;using System.Windows;using System.Windows.Forms;Clipboard.SetText("Hello, clipboard");Clipboard.SetText(txtClipboard.Text);Context
Stack Overflow Q#3546016, score: 983
Revisions (0)
No revisions yet.