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)
{
Clipboard.SetText(DemoText.Text);
}
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)
{
Clipboard.SetText(DemoText.Text);
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)
{
Clipboard.Clear();
}
You can now try all of the buttons together to see how they operate.
3 July 2013