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
Linda HamiltonOriginal
2025-01-03 02:58:38449browse

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");

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

Clipboard.SetText(txtClipboard.Text);

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!

Statement:
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