Windows剪貼簿操作簡單小例
阿新 • • 發佈:2019-01-06
1、複製文字到剪貼簿
CString strText = L"需要複製到剪貼簿的文字"; if ( ::OpenClipboard(m_hWnd) ) { if ( ::EmptyClipboard() )//清空剪貼簿內資料 { int nSize = strText.GetLength()*2+1;//這裡是位元組數,UNICODE編碼每個字元佔2個位元組,後面加上一個\0結尾符. HGLOBAL hMem = ::GlobalAlloc(GHND, nSize); byte* pData=(byte*)::GlobalLock(hMem); memcpy_s(pData, nSize, strData.GetData(), nSize-1); pData[nSize-1]='\0'; ::GlobalUnlock(hMem); ::SetClipboardData(CF_UNICODETEXT, hMem); ::CloseClipboard(); ::GlobalFree(hMem); } }
2、複製點陣圖控制代碼到剪貼簿
//儲存截圖區域點陣圖到剪下板
if( ::OpenClipboard(m_hWnd) )
{
if( ::EmptyClipboard() )
{
HBITMAP hBmp = GetBitmapRect(g_hScreenBmp, m_rect);
::SetClipboardData(CF_BITMAP, hBmp);
DeleteObject(hBmp);
::CloseClipboard();
}
}
3、總的來說,你必須按照這個順序來操作剪貼簿:open ---- empty ---- setdata ----- close。(開啟-清空-設定-關閉)
更多詳細引數介紹可以參考MSDN說明
Remarks OpenClipboard fails if another window has the clipboard open. An application should call the CloseClipboard function after every successful call to OpenClipboard. The window identified by the hWndNewOwner parameter does not become the clipboard owner unless the EmptyClipboard function is called. If an application calls OpenClipboard with hwnd set to NULL, EmptyClipboard sets the clipboard owner to NULL; this causes SetClipboardData to fail.