Wednesday, June 2, 2010

Use Clipboard

In C# you can easily access the clipboard, inserting or reading data.
In this post I will describe how to do so, just focussing on text and images though, which is anyways probably the most used feature.
For managing the clipboard the class System.Windows.Forms.Clipboard is responsible.
The function ContainsText() returns true if text is available in the clipboard, otherwise false.
Consequently ContainsImage() has the same meaning just with images.
GetText() gets the copied text, SetText() sets it.
Similiarly, GetImage() gets the copied image, SetImage() copies one in the clipboard.
The following example code checks on runtime the content of the clipboard, if text is available, this is copied to the textbox textBox1, if an image is available, this is shown in pictureBox1:
if (System.Windows.Forms.Clipboard.ContainsText())
textBox1.Text = System.Windows.Forms.Clipboard.GetText();
if (System.Windows.Forms.Clipboard.ContainsImage())
pictureBox1.Image = System.Windows.Forms.Clipboard.GetImage();

No comments:

Post a Comment