Click here to Skip to main content
6,293,171 members and growing! (11,766 online)
Email Password   helpLost your password?
Desktop Development » Shell and IE programming » Shell Programming     Beginner

Clipboard handling with .NET

By Nishant Sivakumar

An introduction to using the clipboard
C#.NET 1.0, Win2K, WinXP, Dev
Posted:27 Apr 2002
Views:224,271
Bookmarked:75 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
39 votes for this article.
Popularity: 6.76 Rating: 4.25 out of 5

1

2
1 vote, 3.6%
3
8 votes, 28.6%
4
19 votes, 67.9%
5

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.

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.

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

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

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

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 :-

[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.

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);

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Nishant Sivakumar


Member
Nish is a real nice guy living in Atlanta, who has been coding since 1990, when he was 13 years old. Originally from sunny Trivandrum in India, he recently moved to Atlanta from Toronto and is a little sad that he won't be able to play in snow anymore.

Nish has been a Microsoft Visual C++ MVP since October, 2002 - awfully nice of Microsoft, he thinks. He maintains an MVP tips and tricks web site - www.voidnish.com where you can find a consolidated list of his articles, writings and ideas on VC++, MFC, .NET and C++/CLI. Oh, and you might want to check out his blog on C++/CLI, MFC, .NET and a lot of other stuff - blog.voidnish.com

Nish loves reading Science Fiction, P G Wodehouse and Agatha Christie, and also fancies himself to be a decent writer of sorts. He has authored a romantic comedy Summer Love and Some more Cricket as well as a programming book – Extending MFC applications with the .NET Framework.

Nish's latest book C++/CLI in Action published by Manning Publications is now available for purchase. You can read more about the book on his blog.

Despite his wife's attempts to get him into cooking, his best effort so far has been a badly done omelette. Some day, he hopes to be a good cook, and to cook a tasty dinner for his wife.
Location: United States United States

Other popular Shell and IE programming articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 49 (Total in Forum: 49) (Refresh)FirstPrevNext
GeneralClipboard for Web Base Application Pinmemberamyvoon22:56 15 Apr '09  
Generalhow to get the multiple file names from the copied folder from the clipboard C# 2005 PinmemberMember 447950422:46 27 Jan '09  
GeneralClipboard.SetText vs. Clipboard.SetDataObject [modified] Pinmembersmhiker11:49 10 Nov '08  
GeneralNice Article Pinmemberashu_himt4:54 16 Apr '08  
GeneralDoesn't work PinmemberDeebadeebz10:36 11 Apr '08  
GeneralCopying images to clipboard using ASP.net Pinmembertmgovind2:52 8 Apr '08  
GeneralullReferenceException was unhandled <------PROBLEM PinmemberLOLKICA10:50 2 Jul '07  
GeneralThanks PinmemberTodd Smith9:35 2 May '07  
Generalcopy image from clipboard and insert into word doc Pinmemberminad_7865:55 15 Mar '07  
GeneralInteraction c#/c++ Pinmemberruedig6:06 5 Oct '06  
QuestionSTAThread [modified] Pinmemberwurakeem5:27 24 Sep '06  
AnswerRe: STAThread Pinmemberwurakeem12:31 24 Sep '06  
GeneralRe: STAThread PinmemberMember 27652351:12 28 May '08  
GeneralSome Issues PinmemberYaron Sh0:01 4 Sep '06  
GeneralClipboard and Metafiles Pinmemberraastad0:11 5 Apr '06  
GeneralCopy files to clipboard PinsussMaxim Kogan4:13 26 Sep '05  
GeneralRe: Copy files to clipboard PinmemberVertexwahn23:57 19 Dec '05  
GeneralWere the files CUT or COPIED.... PinmemberAndrewVos4:57 17 Aug '05  
GeneralRe: Were the files CUT or COPIED.... Pinmemberalexstnky22:45 30 Aug '05  
GeneralRe: Were the files CUT or COPIED.... PinmemberAJafer1:50 23 Jul '07  
GeneralOne more doubt about Clipboard copy Pinmemberjibesh22:43 17 Jun '05  
GeneralDoesn't Work Pinsussdfhgesart8:29 8 Jun '05  
GeneralRe: Doesn't Work PinmemberAJafer1:49 23 Jul '07  
Generalwell done PinmemberGhazi Al Wadi20:31 14 May '05  
GeneralHow to put metafile on clipboard? Pinmemberhain15:19 14 May '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 27 Apr 2002
Editor: Chris Maunder
Copyright 2002 by Nishant Sivakumar
Everything else Copyright © CodeProject, 1999-2009
Web20 | Advertise on the Code Project