Click here to Skip to main content
15,880,469 members
Articles / Programming Languages / C#
Article

Clipboard handling with .NET

Rate me:
Please Sign up or sign in to vote.
4.72/5 (51 votes)
27 Apr 2002CPOL4 min read 531.6K   6.8K   118   63
An introduction to using the clipboard

The Clipboard

The clipboard is where your data is stored when you copy or cut some text or an image or a file or a folder. The clipboard is common across processes, which means we can use the clipboard as a mechanism to transfer data between two processes. Win32 gave us a Clipboard API with functions like OpenClipboard and GetClipboardData which most of you might be familiar with. In .NET Microsoft has encapsulated the functionality of most of these functions into some classes. The most prominent of these classes is a class which has been named aptly as Clipboard. It's a very simple class with just two functions. In this article, we'll see how to copy/paste text, images and also how to maintain clipboard data in multiple formats.

I'd like to thank James Johnson for his amazing help while I was fiddling with the clipboard. I didn't have a reference book to help me, but that didn't matter much as James more than made up for it. Poor Mike Dunn had to suffer some .NET talk when he walked into Bob's HungOut just as I was discussing an issue with James. Anyway let's get on with things now.

Copying text into the clipboard

The Clipboard class has a SetDataObject function which is used to insert clipboard data. It takes an Object as argument in the single argument overload. In the other overload it takes both an Object and a bool variable, which we can set to true if we want the clipboard to persist even after our application has exited. In our example program we'll use the second overload as that seems to be the more common situation, where we would want other programs to access what we have copied onto the clipboard.

C#
Clipboard.SetDataObject(textBox1.Text,true);

Retrieving text from the clipboard

The Clipboard class also has a

GetDataObject
function which returns an IDataObject. The IDataObject interface has a function called GetDataPresent which we use to determine if the IDataObject has data of a specific format.  We can use the static fields of the DataFormats class to verify that the format we expect is indeed available in the
IDataObject
. If GetDataPresent returns true, we can then use the GetData function to retrieve the data format that we are expecting.

C#
if(Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
    textBox1.Text = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();
else
    textBox1.Text  = "The clipboad does not contain any text";

Image 1

Observe how I have copied some text from Notepad and pasted it into our sample program. You can also copy text from our program and paste it into Notepad. And I hope you like my XP theme and colors as well.

Copying/Retrieving images from the Clipboard

This is exactly the same as in copying and pasting text except that we use the DataFormats.Bitmap format instead of DataFormats.Text

C#
Clipboard.SetDataObject(pictureBox1.Image,true);
C#
if(Clipboard.GetDataObject().GetDataPresent(DataFormats.Bitmap))
    pictureBox1.Image = (Bitmap)Clipboard.GetDataObject().GetData(DataFormats.Bitmap);

Image 2

I have copied from Paint Brush into our sample program. You can then copy something else using Paint Brush, come back to our program, copy the image and paste back into Paint Brush. The image has stretched a bit because I have set the SizeMode  property of the Picture control to StretchImage.

Maintain multiple formats in the Clipboard

There are situations where you are not sure what kind of data the target application of a copy/paste cycle is expecting in the clipboard. In such cases we can maintain multiple data formats in the clipboard, so that the target application can retrieve the data format it's expecting. In our sample, we'll copy both the text in the edit box as well as the image in the picture control into the clipboard. Now you can open Notepad and paste into it the text as well as open Paint Brush and paste into it the bitmap. I have provided a [Paste Both] button for ease of demonstration. Just run a second instance of the sample program and we can paste both the text and the image into the respective controls.

We make use of the DataObject class which implements the IDataObject interface. We call the SetData function twice, each time passing in a different format data. We use the following override of the function :-

C#
[ClassInterface(ClassInterfaceType.None)]
public virtual void SetData(
   string format, //This indicates what type of data this is going to be
   bool autoConvert, //Set this true to allow automatic data format conversions
   object data //The actual data [which is in the format specified above]
);

The code is very straightforward. We create a DataObject object, use SetData twice, once with the text and then with the image, then we add this DataObject to the clipboard.

C#
DataObject m_data = new DataObject();
m_data.SetData(DataFormats.Text,true,textBox1.Text);
m_data.SetData(DataFormats.Bitmap,true,pictureBox1.Image);
Clipboard.SetDataObject(m_data,true);

Image 3

Now you can paste both into Notepad as well as into any Graphics application that allows you to paste a Bitmap into it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Nish Nishant is a technology enthusiast from Columbus, Ohio. He has over 20 years of software industry experience in various roles including Chief Technology Officer, Senior Solution Architect, Lead Software Architect, Principal Software Engineer, and Engineering/Architecture Team Leader. Nish is a 14-time recipient of the Microsoft Visual C++ MVP Award.

Nish authored C++/CLI in Action for Manning Publications in 2005, and co-authored Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his WordPress blog. Nish is experienced in technology leadership, solution architecture, software architecture, cloud development (AWS and Azure), REST services, software engineering best practices, CI/CD, mentoring, and directing all stages of software development.

Nish's Technology Blog : voidnish.wordpress.com

Comments and Discussions

 
AnswerRe: STAThread Pin
wurakeem24-Sep-06 11:31
wurakeem24-Sep-06 11:31 
GeneralRe: STAThread Pin
Member 276523528-May-08 0:12
Member 276523528-May-08 0:12 
GeneralSome Issues Pin
Yaron Sh3-Sep-06 23:01
Yaron Sh3-Sep-06 23:01 
GeneralClipboard and Metafiles Pin
raastad4-Apr-06 23:11
raastad4-Apr-06 23:11 
GeneralCopy files to clipboard Pin
maxim.kogan@gmail.com26-Sep-05 3:13
maxim.kogan@gmail.com26-Sep-05 3:13 
GeneralRe: Copy files to clipboard Pin
Vertexwahn19-Dec-05 22:57
Vertexwahn19-Dec-05 22:57 
GeneralWere the files CUT or COPIED.... Pin
AndrewVos17-Aug-05 3:57
AndrewVos17-Aug-05 3:57 
GeneralRe: Were the files CUT or COPIED.... Pin
alexstnky30-Aug-05 21:45
alexstnky30-Aug-05 21:45 
GeneralRe: Were the files CUT or COPIED.... Pin
AJafer23-Jul-07 0:50
AJafer23-Jul-07 0:50 
GeneralOne more doubt about Clipboard copy Pin
Jibesh17-Jun-05 21:43
professionalJibesh17-Jun-05 21:43 
GeneralDoesn't Work Pin
dfhgesart8-Jun-05 7:29
dfhgesart8-Jun-05 7:29 
GeneralRe: Doesn't Work Pin
AJafer23-Jul-07 0:49
AJafer23-Jul-07 0:49 
Generalwell done Pin
Ghazi H. Wadi14-May-05 19:31
Ghazi H. Wadi14-May-05 19:31 
QuestionHow to put metafile on clipboard? Pin
hain14-May-05 14:19
hain14-May-05 14:19 
AnswerRe: How to put metafile on clipboard? Pin
Liu Junfeng6-Jun-05 5:59
Liu Junfeng6-Jun-05 5:59 
GeneralRetrieve all objects in clipboard Pin
Alon Ronen22-Feb-05 22:16
Alon Ronen22-Feb-05 22:16 
QuestionCopy selected text? Pin
Member 11480879-Dec-04 9:51
Member 11480879-Dec-04 9:51 
AnswerRe: Copy selected text? Pin
Stefan Prodan12-Mar-05 1:28
Stefan Prodan12-Mar-05 1:28 
GeneralText Widget and Image Widget Pin
Anonymous9-Nov-04 7:35
Anonymous9-Nov-04 7:35 
GeneralRetreiving a CF_BITMAP format from Clipboard Pin
Anonymous11-Apr-04 10:22
Anonymous11-Apr-04 10:22 
GeneralRe: Retreiving a CF_BITMAP format from Clipboard Pin
sabrown10017-Oct-07 12:13
sabrown10017-Oct-07 12:13 
Generalgdi+ and clipboard Pin
cowen1-Aug-03 2:45
cowen1-Aug-03 2:45 
GeneralCut and Paste Files from Explorer Pin
Alex Cherkasov24-Jul-03 6:01
Alex Cherkasov24-Jul-03 6:01 
Generala Good Job!!! Pin
Vitaliy Vorontsov18-Sep-02 23:37
Vitaliy Vorontsov18-Sep-02 23:37 
GeneralRe: a Good Job!!! Pin
Nish Nishant18-Sep-02 23:43
sitebuilderNish Nishant18-Sep-02 23:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.