Click here to Skip to main content
Click here to Skip to main content

Clipboard handling with .NET

By , 27 Apr 2002
 

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Nish Sivakumar
United States United States
Member
Nish is a real nice guy who has been writing code since 1990 when he first got his hands on an 8088 with 640 KB RAM. Originally from sunny Trivandrum in India, he has been living in various places over the past few years and often thinks it’s time he settled down somewhere.
 
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.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionHow change Color Background of Clipboard?memberalias13679214 Mar '13 - 0:12 
i'm using a Picturebox and a Richtextbox.
copy Image from Picturebox in Clipboad with this Code:
Clipboard.Clear();
Clipboard.SetImage(pictureBox1.Image);
 
and Paste Image from Clipboard to Richtextbox with this Code:
DataFormats.Format myFormat = DataFormats.GetFormat(DataFormats.Bitmap);
if (richTextBox1.CanPaste(myFormat))
{
richTextBox1.Paste(myFormat);
}
else
{
MessageBox.Show("The data format that you attempted to paste is not supported by this control.");
}
 
but when Paste image from Clipboard to Richtextbox, Color Background image is Blue!
See this Image:
http://barnamenevis.org/attachment.php?attachmentid=100587&d=1361887709[^]
 
So How change Color Background of Clipboard?

GoodLuck
Questionhave copied tabs seprated string, now how to put each string in a different textbox?memberMember 89732142 Jan '13 - 12:30 
hi friends
i have copied tabs separated string (copied data from excel file) , now how to put each string in a different textbox? plz help thanks
 
Desired output snapshot.
GeneralMy vote of 4memberCodeMan482531 Jul '12 - 21:55 
nice
tx
GeneralMy vote of 5memberdavod_ir7 Jan '12 - 1:23 
EASY TO USE &
QuestionCan it be applied to web form?memberping12343 Feb '10 - 19:34 
Is it possible to applied this feature to web form?
QuestionHow to copy Bitmap with Transparency (Alpha Channel) into the clipboard ?memberSLA8028 Dec '09 - 18:52 
How to copy Bitmap with Transparency (Alpha Channel) into the clipboard ?
Is there any simple solution like SetData() method? (without loads of unsafe WinAPI)?
 
I found somewhere this solution, but it's not working. Frown | :( When I run it, nothing happens:
 
MemoryStream ms = new MemoryStream();
ImageWithAlphaChannel.Save(ms, ImageFormat.Png);
IDataObject dataObject = new DataObject();
dataObject.SetData("PNG", false, ms);
Clipboard.SetDataObject(dataObject, false);

AnswerRe: How to copy Bitmap with Transparency (Alpha Channel) into the clipboard ?membervanhalsen18 Jan '10 - 7:07 
Hi,
 
i have the same issue and found the same code and receive the same result. Have you been able to solve it? Or does someone else know how to handle this with VB
 
Thanks
AnswerRe: How to copy Bitmap with Transparency (Alpha Channel) into the clipboard ?memberAndy 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 Pastemembereg_Anubhava27 Aug '09 - 23:14 
Hello Nishant,
Is it possible to handle Paste information ?
 
If you can think then I Can.

QuestionWon't paste the image into Open Office Writer?memberldcr11 Aug '09 - 14:05 
Hi,
 
I wrote some similar code and found it works everywhere except Open Office - well the text works, but not the images - not sure if anyone has ideas as to why?
 
cheers
Lance
GeneralClipboard for Web Base Applicationmemberamyvoon15 Apr '09 - 21:56 
Hi, anyone know how to do this in web based application?
Questionhow to get the multiple file names from the copied folder from the clipboard C# 2005memberMember 447950427 Jan '09 - 21:46 
how to get the multiple file names from the copied folder from the clipboard C# 2005
GeneralClipboard.SetText vs. Clipboard.SetDataObject [modified]membersmhiker10 Nov '08 - 10:49 
First of all, thanks to 'The Code Project' for showing the Clipboard.SetDataObject.
 
What I wanted to do was to copy some Text to the Clipboard. I first used the Clipboard.SetText method, and for some reason it had a weird quirk - it did Copy it to the Clipboard (If opening the Clipboard - it was there), but Opening Microsoft Word - Paste was DISABLED, if opening Notepad - Paste was available.
 
I then used the Clipboard.SetDataObject method (as is posted on the Code Project page), it WORKED like it was supposed to. Code fragments below.
 
//Clipboard.SetText Method: (It did not work)
Clipboard.SetText(txtTempInput.Text + " = " + txtAnswer.Text);
 
//Clipboard.SetDataObject Method: (it DID work)
Clipboard.SetDataObject(txtTempInput.Text + " = " + txtAnswer.Text,true);
 
I thought that SetText was supposed to work when Copying Text, so my question is, why does SetDatObject work and not SetText?
 
modified on Thursday, November 13, 2008 12:41 PM

GeneralNice Articlememberashu_himt16 Apr '08 - 3:54 
This is fantastic job. I need it
GeneralDoesn't workmemberDeebadeebz11 Apr '08 - 9:36 
The project had to be converted to Visual Studio 2005 to be compiled. And this copy thing doesn't work what so ever. Kind of a waste of time.
GeneralCopying images to clipboard using ASP.netmembertmgovind8 Apr '08 - 1:52 
Nishant
 
I have a web page developed using ASP.net that displays the images. These images need to copied to the client system's clipboard. So far all my attempts have been in vain. I have the URL of the image, can I do anything to store the image (not just the URL) ?
 
Thanks
 
Govind
GeneralullReferenceException was unhandled <------PROBLEMmemberLOLKICA2 Jul '07 - 9:50 
This is the problem....
 
if(Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
textBox1.Text = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();
else
textBox1.Text = "The clipboad does not contain any text";
 
When compiler hits that if statement, it throws an exception...
 
"NullReferenceException was unhandled"Mad | :mad:
 
What should I do ???????
 
Mad | :mad: Mad | :mad:
GeneralThanksmemberTodd Smith2 May '07 - 8:35 
Just what I was looking for. Copy. Paste. Done Big Grin | :-D
 
Todd Smith

Generalcopy image from clipboard and insert into word docmemberminad_78615 Mar '07 - 4:55 
Hello,
Could anyone tell me how to copy an image from the
Clipboard and insert this *.jpeg into a word document.
I am using VC.net 2003 and word 2003.
Please help.
Thanks
 
Minad
GeneralInteraction c#/c++memberruedig5 Oct '06 - 5:06 
I want Copy or D&D data from c# to c++
I made a xml serializer/deserializer of certain classes in both c++ and c#.
Then I will call the following code in c# to start the drag or copy
 
DataFormats.Format myFormat = DataFormats.GetFormat("My Format");
IoChannel ioc = new IoChannel();
ioc.AddressString = str;
StringWriter lStream = new StringWriter();
XmlSerializer lSerializer = new XmlSerializer(typeof(IoChannel));
lSerializer.Serialize(lStream, ioc);
DataObject dataObj = new DataObject(myFormat.Name, lStream.ToString());
DragDropEffects dropEffect = grid.DoDragDrop(dataObj, DragDropEffects.Move);
 
in drag enter in c++

HGLOBAL hMem;
// Get the data from COleDataObject
hMem = pDataObject->GetGlobalData(RegisterClipboardFormat(TEXT("MyFormat")));
if (hMem != NULL)
{
LPDATAOBJECT iData;
iData = = (LPDATAOBJECT )GlobalLock(hMem);
 
I can see the xml stream (string) in the memory at a certain offset. but when i try to access iData the application crashes. is the object not a LPDATAOBJECT ?
 
Did anybody solve the problem, or am I just to ...
QuestionSTAThread [modified]memberwurakeem24 Sep '06 - 4:27 
I cannot retrieve Clipboard data from another thread created in my win form.
I need a method that will run in another thread, aside from the main GUI thread, checking every second if there's clipboard data.
I came up with the following code. Notice my comments, the clipboard data can only be retrieved in the main GUI thread, not in the one desired. Per MSDN, I also added the <STAThread> attribute but still no help.
' This method will correctly retrieve clipboard data
      Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Try
                  txtHeaders.Text = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString()   'THIS WORKS!
                  Dim fnp As New MethodInvoker(AddressOf HandleClipBoardCopy)   'Now let's try the same thing in another thread
                  fnp.BeginInvoke(Nothing, Nothing)
            Catch ex As Exception
                  MessageBox.Show(ex.Message + vbCrLf + ex.StackTrace)
            End Try
      End Sub
 
' This method will throw exception saying "object not set to an instance" because Clipboard.GetDataObject() returns nothing (null )
      <STAThread()> Private Sub HandleClipBoardCopy()
            MessageBox.Show("HELLO!")
            Dim blnDone As Boolean = False
            Try
                  While Not blnDone
                        If (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text)) Then   'THROWS exception here.
                              txtHeaders.Text = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString()
                        End If
                        Thread.Sleep(1000)
                  End While
            Catch ex As Exception
                  MessageBox.Show(ex.Message + vbCrLf + ex.StackTrace)
            End Try
      End Sub
 

 
-- modified at 17:17 Sunday 24th September, 2006
AnswerRe: STAThreadmemberwurakeem24 Sep '06 - 11:31 
found my own solution. The vs.net 2003 macro attribute does not work. instead you must create a separate thread and declare the appartment to be STA.
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=86082&SiteID=1
basically, changing
 

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
Dim fnp As New MethodInvoker(AddressOf HandleClipBoardCopy)
fnp.BeginInvoke(Nothing, Nothing)
Catch ex As Exception
MessageBox.Show(ex.Message + vbCrLf + ex.StackTrace)
End Try
End Sub
 
to
 
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
Dim ClipBoardThread As System.Threading.Thread = New System.Threading.Thread(AddressOf HandleClipBoardCopy)
With ClipBoardThread
.ApartmentState = System.Threading.ApartmentState.STA
.IsBackground = True
.Start()
End With
Catch ex As Exception
MessageBox.Show(ex.Message + vbCrLf + ex.StackTrace)
End Try
End Sub
GeneralRe: STAThreadmemberMember 276523528 May '08 - 0:12 
this one worked for me too, so here is a sample code in c#:
 
class Program
{
	static void Main(string[] args)
	{
		string path = @"c:\WINDOWS\system32\drivers\etc\hosts";
		Thread t = new Thread(new ThreadStart(delegate()
			{
				string text = File.ReadAllText(path);
				Clipboard.SetText(text);
			}));
 
		t.SetApartmentState(ApartmentState.STA); // t.ApartmentState is depracated
		t.Start();
 
		t.Join(); // so the application wouldn't stop
		Console.WriteLine("Clipboard text set");
	}
}

GeneralSome IssuesmemberYaron Sh3 Sep '06 - 23:01 
The common task is to copy selected text. The form's active control might be label, list item or other and not all of them have the SelectedText property.
Normal copy should handle all these situations.
This article doesn't provide the common functionality basics.
All I can think of right now is some factory that can identify the control type and then do copy for it's content. (Selected text for text based controls, images for image based controls etc.).
GeneralClipboard and Metafilesmemberraastad4 Apr '06 - 23:11 
That would be really great if someone could solve the metafile-on-clipboard problem in .NET v2.0. The worst thing is that it seems difficult to write a GDI (as opposed to GDI+)-based function to do it also, because Graphics::GetHdc() doesnt work well with GDI, as far as I have experienced.

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 28 Apr 2002
Article Copyright 2002 by Nish Sivakumar
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid