VC 剪贴板操作
程序里用到了操作剪贴板的函数,而一直有个问题未能解决。有时会出现莫名其妙的异常。比如我把文本拷贝到剪贴板,之后我的编辑框竟然不能输入文本,即使可以输入,也是一推乱码。今天终于找到根源了。就是多了一句代码GlobalFree 害得我调试惨了。唉!感叹!忏悔一身的业障,才招来今日的遇事不顺!阿弥陀佛!
MSDN里面说得很清楚了:
After SetClipboardData is called, the system owns the object identified by the hMem parameter. The application can read the data, but must not free the handle or leave it locked. If the hMem parameter identifies a memory object, the object must have been allocated using the GlobalAlloc function with the GMEM_MOVEABLE and GMEM_DDESHARE flags.
我自作聪明调用了GlobalFree所以出现了意想不到的bug。
一、设置剪贴板文本
/**************************************************************************** 设置剪贴板文本 ****************************************************************************/ bool SetClipBoardText(const TCHAR* text,HWND hWnd) { ASSERT(hWnd); //打开剪贴板 if ( !::OpenClipboard(hWnd) ) return false; //empties the clipboard and frees handles to data in the clipboard if ( !EmptyClipboard() ) { CloseClipboard(); return false; } //get text length int len=_tcslen(text); //After SetClipboardData is called, the system owns the object identified by the hMem parameter. //The application can read the data, but must not free the handle or leave it locked. If the //hMem parameter identifies a memory object, the object must have been allocated using the //GlobalAlloc function with the GMEM_MOVEABLE and GMEM_DDESHARE flags. HANDLE hClip=GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE,(len+1)*sizeof(TCHAR)); if (hClip==NULL) { CloseClipboard(); return false; } //locks a global memory object and returns a pointer to the first byte of the object's memory block TCHAR* pBuf=(TCHAR*)GlobalLock(hClip); if (pBuf==NULL) { GlobalFree(hClip); CloseClipboard(); return fals