本文演示如何使用 Visual C++ 将超文本标记语言 (HTML) 代码添加到 Microsoft Windows 剪贴板。
原始产品版本:
Visual C++
原始 KB 编号:
274308
本文包含一个示例函数,可在应用程序中使用该函数来简化将 HTML 代码添加到剪贴板的过程。
HTML 具有自己的称为 HTML 格式的剪贴板格式 (CF_HTML) 可用于向其他应用程序(如 Excel、Word 或其他 Office 应用程序)提供数据。
CF_HTML完全是一种基于文本的格式,其中包括说明、上下文和该上下文中的片段。 生成要发送到剪贴板的数据时,必须包含数据说明,以指示剪贴板版本以及上下文和片段的偏移量。 计算偏移量可能很困难。 但是,可以使用以下例程来简化此任务。
有关详细信息,请参阅
HTML 剪贴板格式
。
// CopyHtml() - Copies given HTML to the clipboard.
// The HTML/BODY blanket is provided, so you only need to
// call it like CallHtml("<b>This is a test</b>");
void CopyHTML(char *html)
// Create temporary buffer for HTML header...
char *buf = new char [400 + strlen(html)];
if(!buf) return;
// Get clipboard id for HTML format...
static int cfid = 0;
if(!cfid) cfid = RegisterClipboardFormat("HTML Format");
// Create a template string for the HTML header...
strcpy(buf,
"Version:0.9\r\n"
"StartHTML:00000000\r\n"
"EndHTML:00000000\r\n"
"StartFragment:00000000\r\n"
"EndFragment:00000000\r\n"
"<html><body>\r\n"
"<!--StartFragment -->\r\n");
// Append the HTML...
strcat(buf, html);
strcat(buf, "\r\n");
// Finish up the HTML format...
strcat(buf,
"<!--EndFragment-->\r\n"
"</body>\r\n"
"</html>");
// Now go back, calculate all the lengths, and write out the
// necessary header information. Note, wsprintf() truncates the
// string when you overwrite it so you follow up with code to replace
// the 0 appended at the end with a '\r'...
char *ptr = strstr(buf, "StartHTML");
wsprintf(ptr+10, "%08u", strstr(buf, "<html>") - buf);
*(ptr+10+8) = '\r';
ptr = strstr(buf, "EndHTML");
wsprintf(ptr+8, "%08u", strlen(buf));
*(ptr+8+8) = '\r';
ptr = strstr(buf, "StartFragment");
wsprintf(ptr+14, "%08u", strstr(buf, "<!--StartFrag") - buf);
*(ptr+14+8) = '\r';
ptr = strstr(buf, "EndFragment");
wsprintf(ptr+12, "%08u", strstr(buf, "<!--EndFrag") - buf);
*(ptr+12+8) = '\r';
// Now you have everything in place ready to put on the clipboard.
// Open the clipboard...
if(OpenClipboard(0))
// Empty what's in there...
EmptyClipboard();
// Allocate global memory for transfer...
HGLOBAL hText = GlobalAlloc(GMEM_MOVEABLE |GMEM_DDESHARE, strlen(buf)+4);
// Put your string in the global memory...
char *ptr = (char *)GlobalLock(hText);
strcpy(ptr, buf);
GlobalUnlock(hText);
::SetClipboardData(cfid, hText);
CloseClipboard();
// Free memory...
GlobalFree(hText);
// Clean up...
delete [] buf;
使用此函数将 HTML 代码片段复制到剪贴板时,可能如以下示例所示:
char *html =
"<b>This is a test</b><hr>"
"<li>entry 1"
"<li>entry 2";
CopyHTML(html);
使用将 HTML 代码发送到剪贴板的方法可能对 Office 自动化客户端特别有利。 例如,如果你的自动化客户端需要为 Excel 中的单元格或 Word 中的段落生成格式化数据,则可以在 HTML 代码中生成数据,将其发送到剪贴板,然后将其粘贴到应用程序中。 使用此方法可以减少对自动化客户端的进程外调用数。