Click here to Skip to main content
15,860,859 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 530.3K   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

 
GeneralMy vote of 5 Pin
Gary R. Wheeler3-Jan-20 3:46
Gary R. Wheeler3-Jan-20 3:46 
Questionpaste method of worksheet class failed in vb.bet Pin
Member 1387063221-Oct-18 19:49
Member 1387063221-Oct-18 19:49 
GeneralMy vote of 1 Pin
Oğuzhan Türk11-May-15 23:11
Oğuzhan Türk11-May-15 23:11 
QuestionGetting null Pin
Stephin Francis22-Dec-14 1:46
Stephin Francis22-Dec-14 1:46 
QuestionHow change Color Background of Clipboard? Pin
alias13679214-Mar-13 0:12
alias13679214-Mar-13 0:12 
Questionhave copied tabs seprated string, now how to put each string in a different textbox? Pin
Member 89732142-Jan-13 12:30
Member 89732142-Jan-13 12:30 
GeneralMy vote of 4 Pin
CodeMan482531-Jul-12 21:55
CodeMan482531-Jul-12 21:55 
GeneralMy vote of 5 Pin
davod_ir7-Jan-12 1:23
davod_ir7-Jan-12 1:23 
QuestionCan it be applied to web form? Pin
ping12343-Feb-10 19:34
ping12343-Feb-10 19:34 
QuestionHow to copy Bitmap with Transparency (Alpha Channel) into the clipboard ? Pin
SLA8028-Dec-09 18:52
SLA8028-Dec-09 18:52 
AnswerRe: How to copy Bitmap with Transparency (Alpha Channel) into the clipboard ? Pin
vanhalsen18-Jan-10 7:07
vanhalsen18-Jan-10 7:07 
AnswerRe: How to copy Bitmap with Transparency (Alpha Channel) into the clipboard ? Pin
Andy Missico9-May-10 10:39
Andy Missico9-May-10 10:39 
The format PNG only works for applications that understand it. Microsoft Office 2003 and Microsoft Office 2007 understand it, but know of no other applications that support it.
QuestionHow to Handle Clipboard Paste Pin
Anubhava Dimri27-Aug-09 23:14
Anubhava Dimri27-Aug-09 23:14 
QuestionWon't paste the image into Open Office Writer? Pin
Lance Roberts11-Aug-09 14:05
Lance Roberts11-Aug-09 14:05 
GeneralClipboard for Web Base Application Pin
amyvoon15-Apr-09 21:56
amyvoon15-Apr-09 21:56 
Questionhow to get the multiple file names from the copied folder from the clipboard C# 2005 Pin
Member 447950427-Jan-09 21:46
Member 447950427-Jan-09 21:46 
GeneralClipboard.SetText vs. Clipboard.SetDataObject [modified] Pin
smhiker10-Nov-08 10:49
smhiker10-Nov-08 10:49 
GeneralNice Article Pin
ashu_himt16-Apr-08 3:54
ashu_himt16-Apr-08 3:54 
GeneralDoesn't work Pin
Deebadeebz11-Apr-08 9:36
Deebadeebz11-Apr-08 9:36 
GeneralCopying images to clipboard using ASP.net Pin
tmgovind8-Apr-08 1:52
tmgovind8-Apr-08 1:52 
GeneralullReferenceException was unhandled <------PROBLEM Pin
LOLKICA2-Jul-07 9:50
LOLKICA2-Jul-07 9:50 
GeneralThanks Pin
Todd Smith2-May-07 8:35
Todd Smith2-May-07 8:35 
Generalcopy image from clipboard and insert into word doc Pin
minad_78615-Mar-07 4:55
minad_78615-Mar-07 4:55 
GeneralInteraction c#/c++ Pin
ruedig5-Oct-06 5:06
ruedig5-Oct-06 5:06 
QuestionSTAThread [modified] Pin
wurakeem24-Sep-06 4:27
wurakeem24-Sep-06 4:27 

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.