且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将图像保存到剪贴板

更新时间:2023-09-11 19:07:52

我将从文档开始:MSDN上的剪贴板 [
I would start with the documentation: Clipboard at MSDN[^]. You probably have to use a private clipboard format, for your data.


我看过剪贴板文档,该文档在此处显示了将文本粘贴到剪贴板的示例: ^ ]

一切都很好,但是我如何用如上所述的图像完成相同的操作?
I have looked at the clipboard documentation which shows an example of pasting text to the clipboard here: Using the Clipboard (Windows)[^]

That is all good but how do I accomplish the same with the image as described above?


如MSDN文章使用剪贴板中所述,您必须复制数据分配到已分配的全局内存,并调用SetClipboardData传递剪贴板格式和全局内存句柄.

因为没有用于PNG图像的标准剪贴板格式,所以您必须使用 RegisterClipboardFormat函数注册剪贴板格式href ="https://technet.microsoft.com/en-us/library/ms649049.aspx"> RegisterClipboardFormat函数 [ ^ ].常用的是"PNG"和"image/png"(MIME类型).

将图像作为文件时,将其加载到分配的内存中(未经错误检查的未经测试的示例代码):
As explained in the MSDN article Using the Clipboard, you have to copy the data to allocated global memory and call SetClipboardData passing the clipboard format and the global memory handle.

Because there is no standard clipboard format for PNG images, you have to register a clipboard format using the RegisterClipboardFormat function[^]. Commonly used are "PNG" and "image/png" (the MIME type).

When having the image as file, load it into the allocated memory (untested example code without error checks):
// Get the file size
struct _stat st;
stat(fileName, &st);
// Allocate buffer and read data
HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, st.st_size);
LPVOID pGlobal = GlobalLock(hGlobal);
FILE *f = fopen(fileName, "rb");
fread(pGlobal, 1, st.st_size, f);
fclose(f);
GlobalUnlock(hGlobal);
// Register clipboard format
UINT cf = RegisterClipboardFormat("PNG");
// Put it on the clipboard.
// The global memory is owned by the clipboard and will be freed when
//  new data is put on the clipboard.
OpenClipboard(hWnd);
EmptyClipboard();
SetClipboardData(cf, hGlobal);
CloseClipboard();


使用MFC时,还可以使用CImage类将PNG图像创建为IStream,然后使用COleDataSource类将其放置在剪贴板上.


When using MFC, you can also use the CImage class to create the PNG image as IStream and put that on the clipboard using the COleDataSource class.