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"?
You'll need a namespace declaration:
using System.Windows.Forms;
OR for WPF:
using System.Windows;
To copy an exact string (literal in this case):
Clipboard.SetText("Hello, clipboard");
To copy the contents of a textbox:
Clipboard.SetText(txtClipboard.Text);
See here for an example. Or... Official MSDN documentation or Here for WPF.
Clipboard.SetText("hello");
You'll need to use the System.Windows.Forms
or System.Windows
namespaces for that.
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:
- In Solution Explorer, expand your console project.
- Right-click References, then click Add Reference...
- In the Assemblies group, under Framework, select
System.Windows.Forms
. - 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)
{
// ...
}
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.
来源:https://stackoverflow.com/questions/3546016/how-to-copy-data-to-clipboard-in-c-sharp