ARTICLE

Copying and Pasting on Clipboard using C#

Posted by Mahesh Chand Articles | Windows Controls C# February 23, 2001
If you use CTRL+C, some data or files are copied to a system clipboard and stored in system memory and when you use CTRL+V, the data is copied back to wherever you paste it. The Clipboard class provides functionality to place and retrieve data from the system clipboard. Usually
Reader Level:
Download Files:
 

If you use CTRL+C, some data or files are copied to a system clipboard and stored in system memory and when you use CTRL+V, the data is copied back to wherever you paste it. The Clipboard class provides functionality to place and retrieve data from the system clipboard.

Storing and Retrieving Data

Clipboard has static methods to copy and paste data. The SetDataObject method is used to store data that is in object format on the clipboard. The following code snippet copies selected text from a RichTextBoc control to the clipboard.
 

Clipboard.SetDataObject(richTextBox1.SelectedText);

The GetDataObject method gets the data that is stored on the clipboard. The following code snippet gets data from the clipboard and displays in a Label control.

// Retrieves data

IDataObject iData = Clipboard.GetDataObject();

// Is Data Text?

if (iData.GetDataPresent(DataFormats.Text))

        label1.Text = (String)iData.GetData(DataFormats.Text);

else

    label1.Text = "Data not found.";

Clear Clipboard


Clear method removes all data from the Clipboard.

Clipboard.Clear();


Summary

The Clipboard class provides methods to save and retrieve data from system clipboard.

Article Extensions
Contents added by Mahesh Chand on Jun 15, 2010
Copy and Paste Text: MSDN Example

// Demonstrates SetText, ContainsText, and GetText. public String SwapClipboardHtmlText(String replacementHtmlText)
{
String returnHtmlText = null;
if (Clipboard.ContainsText(TextDataFormat.Html))
{
returnHtmlText = Clipboard.GetText(TextDataFormat.Html);
Clipboard.SetText(replacementHtmlText, TextDataFormat.Html);
}
return returnHtmlText;
}
Contents added by Mahesh Chand on Jun 15, 2010

Copy and Paste Images: MSDN Sample

// Demonstrates SetImage, ContainsImage, and GetImage. public System.Drawing.Image SwapClipboardImage(
System.Drawing.Image replacementImage)
{
System.Drawing.Image returnImage = null;
if (Clipboard.ContainsImage())
{
returnImage = Clipboard.GetImage();
Clipboard.SetImage(replacementImage);
}
return returnImage;
}
COMMENT USING