首页 > 代码库 > Windows剪贴板操作简单小例

Windows剪贴板操作简单小例

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=http://www.mamicode.com/(byte*)::GlobalLock(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.



Windows剪贴板操作简单小例