Home > Backend Development > C++ > How Do I Copy Data to the System Clipboard in C#?

How Do I Copy Data to the System Clipboard in C#?

Linda Hamilton
Release: 2025-01-03 02:58:38
Original
418 people have browsed it

How Do I Copy Data to the System Clipboard in C#?

Copying Data to the System Clipboard in C#

In C#, accessing the system clipboard requires selecting the appropriate namespace based on the application type and ensuring the Main function (if applicable) is attributed with [STAThread]. Here's a breakdown:

  • WinForms: Use the System.Windows.Forms namespace and add the [STAThread] attribute to Main.
  • WPF: Utilize the System.Windows namespace.
  • Console: Include a reference to System.Windows.Forms, use the System.Windows.Forms namespace, and add the [STAThread] attribute to Main.

To copy a literal string to the clipboard:

Clipboard.SetText("Hello, clipboard");
Copy after login

For copying the contents of a textbox, either use TextBox.Copy() or:

Clipboard.SetText(txtClipboard.Text);
Copy after login

Note that the clipboard is a desktop UI concept, so accessing it from server-side code (e.g., ASP.Net) will only affect values on the server and not impact the user's browser.

Additionally, ensure that the current thread is set to a single thread apartment (STA) to avoid exceptions related to Clipboard access.

The above is the detailed content of How Do I Copy Data to the System Clipboard in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template