Windows Code Snippets

Visual C


Save the Clipboard to a file; handles text (CF_TEXT) and bitmaps (CF_DIB)

void WriteClipboardToFile(HWND hWnd,char *szFileName)
{
	char			*ptr;
	HANDLE			hndl;
	HANDLE			hFile;
	DWORD			ioAmount;
	if (*szFileName) SetWindowText(hWnd,szFileName);
	if ((hFile=CreateFile(szFileName,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_ALWAYS,FILE_FLAG_SEQUENTIAL_SCAN|FILE_ATTRIBUTE_NORMAL,NULL))!=INVALID_HANDLE_VALUE) {
		OpenClipboard(hWnd);
		if (IsClipboardFormatAvailable(CF_TEXT)) {
			if (hndl=GetClipboardData(CF_TEXT)) {
				ptr=(char*)GlobalLock(hndl);
				if (WriteFile(hFile,ptr,strlen(ptr),&ioAmount,NULL)!=TRUE)
					TraceLastError(hWnd);
				GlobalUnlock(hndl);
			}
		} else if (IsClipboardFormatAvailable(CF_DIB)) {
			BITMAPFILEHEADER	bmh;
			DWORD				ioAmount,Error;
			HGLOBAL				hGlb;
			void				*lpBuf;
			DWORD				lpSize;
//			DWORD				iDIBSize,iBitSize,iPalSize;
			memset(&bmh,0,sizeof bmh);
			hGlb = GetClipboardData(CF_DIB);
			lpBuf = GlobalLock(hGlb);
			lpSize = GlobalSize(hGlb);
			bmh.bfType = ((WORD) ('M' << 8) | 'B');    
			bmh.bfSize = lpSize + sizeof bmh;
			bmh.bfReserved1    = 0;
			bmh.bfReserved2    = 0;
			bmh.bfOffBits = (DWORD) sizeof bmh + sizeof(BITMAPINFOHEADER);
			if (WriteFile(hFile,&bmh,sizeof bmh,&ioAmount,NULL)!=TRUE)
				TraceLastError(hWnd);
			if (WriteFile(hFile,lpBuf,lpSize,&ioAmount,NULL)!=TRUE)
				TraceLastError(hWnd);
			GlobalUnlock(hGlb);
		}
		CloseClipboard();
		CloseHandle(hFile);
	} else TraceLastError(hWnd);
}

Display the last error message

static void TraceLastError(HWND hWnd)
{
	char * lpMsgBuffer;
	DWORD dwErr;
	dwErr = GetLastError();    //now get the error code and format it...
	FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,NULL,dwErr,MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),(LPTSTR)&lpMsgBuffer,0,NULL);
	MessageBox(hWnd,lpMsgBuffer,"GetLastError()",MB_OK|MB_ICONHAND);
}