一.使用SetClipboardData 方法赋值
首先用GlobalAlloc方法分配内存
- GlobalAlloc 分配内存大小
- GlobalLock 锁定内存
- 拷贝数据到内存中
- GlobalUnlock解锁
OpenClipboard 和CloseClipboard相对应
char szText[]= "Hello, world"; // ANSI characters
if (::OpenClipboard (m_hWnd)) {
::EmptyClipboard ();
HANDLE hData = ::GlobalAlloc (GMEM_MOVEABLE, ::lstrlen (szText) + 1);
LPSTR pData = (LPSTR) ::GlobalLock (hData);
::lstrcpy (pData, szText);
::GlobalUnlock (hData);
::SetClipboardData (CF_TEXT, hData);
::CloseClipboard ();
二.获取Clipboard数据
GetClipboardData 方法获取
GlobalLock 方法可以转型数据(返回是一个VOID指针)
char szText[MAX_PATH];
if (::OpenClipboard (m_hWnd)) {
HANDLE hData = ::GetClipboardData (CF_TEXT);
if (hData != NULL) {
LPCSTR pData = (LPCSTR) ::GlobalLock (hData);
if (::lstrlen (pData) < MAX_PATH)
::lstrcpy (szText, pData);
::GlobalUnlock (hData);
}
::CloseClipboard ();
}
三.Clipboard Formats
不仅仅是字符串复制一个Bitmap图片,
if (::OpenClipboard (m_hWnd)) {
// Make a copy of the bitmap.
BITMAP bm;
CBitmap bitmap;
CBitmap m_bitmap;
m_bitmap.LoadBitmap(IDB_BITMAP2);
m_bitmap.GetObject (sizeof (bm), &bm);
bitmap.CreateBitmapIndirect (&bm);
CDC dcMemSrc, dcMemDest;
dcMemSrc.CreateCompatibleDC (NULL);
CBitmap* pOldBitmapSrc = dcMemSrc.SelectObject (&m_bitmap);
dcMemDest.CreateCompatibleDC (NULL);
CBitmap* pOldBitmapDest = dcMemDest.SelectObject (&bitmap);
dcMemDest.BitBlt (0, 0, bm.bmWidth, bm.bmHeight, &dcMemSrc,
0, 0, SRCCOPY);
HBITMAP hBitmap = (HBITMAP) bitmap.Detach ();
dcMemDest.SelectObject (pOldBitmapDest);
dcMemSrc.SelectObject (pOldBitmapSrc);
// Place the copy on the clipboard.
::EmptyClipboard ();
::SetClipboardData (CF_BITMAP, hBitmap);
::CloseClipboard ();
}
获取复制的Bitmap
if (::OpenClipboard (m_hWnd)) {
HBITMAP hBitmap = (HBITMAP) ::GetClipboardData (CF_BITMAP);
if (hBitmap != NULL) {
// Make a local copy of the bitmap.
}
::CloseClipboard ();
}
四.Private Clipboard Formats
除了内置格式,还可以自定义格式
- UINT nID = ::RegisterClipboardFormat (_T ("Widget"));
- ::SetClipboardData (nID, hData);
- HANDLE hData = ::GetClipboardData (nID);
五.Providing Data in Multiple Formats
可以将多种格式的数据存在Clipboard中
::SetClipboardData (nID, hPrivateData);
::SetClipboardData (CF_BITMAP, hBitmap);
::SetClipboardData (CF_TEXT, hTextData);
六.查询可用Formats
1.判断不同格式(IsClipboardFormatAvailable),注意没用完Clipboard时,不要关闭Clipboard,所以把CloseClipboard放最后
if (::OpenClipboard (m_hWnd)) {
if (::IsClipboardFormatAvailable (nID)) {
// Perfect!
}
else if (::IsClipboardFormatAvailable (CF_TEXT)) {
// Not the best, but I‘ll take it.
}
else if (::IsClipboardFormatAvailable (CF_BITMAP)) {
// Better than nothing.
}
::CloseClipboard ();
}
2.获取后的处理方式同上
if (::OpenClipboard (m_hWnd)) {
if (::IsClipboardFormatAvailable (CF_TEXT)) {
HANDLE hData = ::GetClipboardData (CF_TEXT);
LPCSTR pData = (LPCSTR) ::GlobalLock (hData);
}
::CloseClipboard ();
}
参考:MFC Windows程序设计