问题
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\"?
回答1:
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.
回答2:
Clipboard.SetText("hello");
You'll need to use the System.Windows.Forms
or System.Windows
namespaces for that.
回答3:
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)
{
// ...
}
回答4:
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.
回答5:
Clip.exe is an executable in Windows to set the clipboard. Note that this does not work for other operating systems other than Windows, which still sucks.
/// <summary>
/// Sets clipboard to value.
/// </summary>
/// <param name="value">String to set the clipboard to.</param>
public static void SetClipboard(string value)
{
if (value == null)
throw new ArgumentNullException("Attempt to set clipboard with null");
Process clipboardExecutable = new Process();
clipboardExecutable.StartInfo = new ProcessStartInfo // Creates the process
{
RedirectStandardInput = true,
FileName = @"clip",
};
clipboardExecutable.Start();
clipboardExecutable.StandardInput.Write(value); // CLIP uses STDIN as input.
// When we are done writing all the string, close it so clip doesn't wait and get stuck
clipboardExecutable.StandardInput.Close();
return;
}
来源:https://stackoverflow.com/questions/3546016/how-to-copy-data-to-clipboard-in-c-sharp