Jason Down
Jason Down

Reputation: 22191

How do I copy an image and text to the clipboard as one object?

I'm trying to copy both an image from a file and text from a file to the clipboard. My intention is to then open a word document or an outlook email and paste both the text and the image in one standard paste command (CTRL-V for example). I can do both separately easily enough, but doing them both in one operation doesn't seem to work.

This is how I've got the two working as separate operations (only relevant code lines of course, with try/catch stripped out etc.):

Add Image to Clipboard:

...

Bitmap imageToAdd = new Bitmap(imageFilePath);
Clipboard.SetImage(imageToAdd);

...

Add Text to Clipboard:

...

StreamReader rdr = new StreamReader(textFilePath);
string text = rdr.ReadToEnd();

Clipboard.SetText(text);

...

I'm using c# and .net 2.0 framework and targeting Windows XP (and likely Vista in the near future).

TIA

Upvotes: 5

Views: 7798

Answers (4)

Markus
Markus

Reputation: 839

Adding specific code implementation;

// Load a bitmap without locking it.
private Bitmap LoadBitmapUnlocked(string path)
{
    using (Bitmap bm = new Bitmap(path))
    {
        return new Bitmap(bm);
    }
}

...

string path = 
@"C:\Windows\Web\Wallpaper\Architecture\img13.jpg"; 
DataObject dataObj = new DataObject();
dataObj.SetData(DataFormats.Bitmap, true, LoadBitmapUnlocked(path));
dataObj.SetData(DataFormats.UnicodeText, path);
Clipboard.SetDataObject(dataObj);

Upvotes: 0

Chris Thornton
Chris Thornton

Reputation: 15817

You could use RTF, which could combine text and graphics. Note that you CAN have CF_BITMAP and CF_TEXT on the clipboard at the same time. But it's not useful. You'd get the text when you paste into notepad, you'd get the bitmap when you paste into Paint, and most other apps would pick one or the other, but never both. So it's merely academic. Kind of neat, in the way that transporter malfunctions on Star Trek were neat. But also messy.

Upvotes: 5

GurdeepS
GurdeepS

Reputation: 67273

I noticed only an object can be passed in.

In that case, when the user presses the command to paste, your code could execute two functions, or one function recursively, and each time get the data you want and paste it in.

So, look at looping or recursion.

Upvotes: 1

GurdeepS
GurdeepS

Reputation: 67273

Maybe you could use SetDataObject which requires an Object parameter, you could use an object array?

The object array could hold your required data.

See this link:

http://msdn.microsoft.com/en-us/library/5b8kt5z4.aspx

Upvotes: 1

Related Questions