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”?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are two classes that lives in different assemblies and different namespaces.
WinForms: use following namespace declaration, make sure
Mainis marked with[STAThread]attribute:WPF: use following namespace declaration
console: add reference to
System.Windows.Forms, use following namespace declaration, make sureMainis marked with[STAThread]attribute. Step-by-step guide in another answerTo 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
SetApartmentStateit 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?