This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Programming
.NET 2.0+

Using the Clipboard to Transfer Text

The Windows clipboard is a useful temporary storage area for information that users can use when copying and pasting information within a single application or between programs. The contents of the clipboard can be manipulated from .NET software.

Changing the Clipboard Text

For cut and copy operations you set the contents of the clipboard using the SetText method. The first parameter should contain the new information to be stored. The second argument is optional. It specifies the type of data using a TextDataFormat value.

We can apply this method to the Copy button by adding the following Click event code:

private void CopyButton_Click(object sender, EventArgs e)

The Cut button uses the same code to update the clipboard. It requires an additional line to clear the textbox so that the user sees the appropriate feedback:

private void CutButton_Click(object sender, EventArgs e)
    DemoText.Text = "";

Try adding the two events and running the program to see the results.

Clearing the Clipboard

The last method of interest for this article is Clipboard.Clear, which empties the clipboard entirely. This is less commonly used but does have a valuable role. For example, if your application sets the clipboard's contents to a very large amount of text, this may take up memory unnecessarily. As your software exits you might ask the user if they wish to keep it in the clipboard for use with other applications or clear it to free up the resources.

In our sample we need to connect the method to the Clear button. Double-click the button in the designer to add the Click event and modify it, as shown below.

private void ClearButton_Click(object sender, EventArgs e)

You can now try all of the buttons together to see how they operate.

3 July 2013