Author: Harley Pebley
How to copy an image and text to the clipboard at the same time
Answer:
The clipboard can have multiple items in different formats on it. However, you need
to add the various items to the clipboard using API functions rather than the
Delphi object wrappers. The Delphi wrappers assume they are the only item on the
clipboard and clear everything else off. The following shows one way to put both a
bitmap and text on the clipboard.
1 { ... }2 var3 lBmpFmt: TBMPExportFormat;
4 lTmpBmp: Graphics.TBitmap;
5 lData: THandle;
6 lFormat: Word;
7 lPalette: HPALETTE;
8 lTxtFmt: TSeriesDataText;
9 Data: THandle;
10 DataPtr: Pointer;
11 lTxt: PChar;
12 begin13 Clipboard.Open;
14 try15 {Make sure the clipboard is cleared every time. Someone may have put some16 other formats on it that hide the things we're going to put on it (since 17 there's a search protocol for appropriate types and our types may be lower18 in the protocol and so not be found when it comes time to paste).}19 Clipboard.Clear;
20 {Save as a bitmap}21 lBmpFmt := TBMPExportFormat.Create;
22 try23 lBmpFmt.Panel := Self;
24 lTmpBmp := lBmpFmt.Bitmap;
25 try26 lPalette := 0;
27 lTmpBmp.SaveToClipboardFormat(lFormat, lData, lPalette);
28 SetClipboardData(lFormat, lData);
29 if lPalette <> 0 then30 SetClipboardData(CF_PALETTE, lPalette);
31 finally32 lTmpBmp.Free;
33 end;
34 finally35 lBmpFmt.Free;
36 end;
37 {Save as text}38 lTxtFmt := TSeriesDataText.Create(Self);
39 try40 lTxt := PChar(lTxtFmt.AsString);
41 finally42 lTxtFmt.Free;
43 end;
44 Data := GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, StrLen(lTxt) + 1);
45 try46 DataPtr := GlobalLock(Data);
47 try48 Move(lTxt^, DataPtr^, StrLen(lTxt) + 1);
49 if SetClipboardData(CF_TEXT, Data) = 0 then50 ShowMessage(SysErrorMessage(GetLastError));
51 finally52 GlobalUnlock(Data);
53 end;
54 except55 GlobalFree(Data);
56 raise;
57 end;
58 finally59 Clipboard.Close;
60 end;
61 end;