How to snap an OpenGL client and send it to the clipboard

本文介绍了一种方法,能够捕获OpenGL客户端区域的画面并将其发送到剪贴板,以便于在图像编辑器、PowerPoint等应用中使用。该方法通过获取OpenGL客户端的几何尺寸,创建位图并读取像素数据,最终将位图信息打包为DIB格式放入剪贴板。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

How to snap an OpenGL client and send it to the clipboard

This article demonstrates how to snap an OpenGL client and send it to ClipBoard. 

We suppose your screen configuration is set to true color. 
We could send the same buffer in a .bmp file in a few lines too....
// Snap OpenGL client and send it to ClipBoard 
// so that you can insert it in your favorite 
// image editor, Powerpoint, etc... 
// Replace CRenderView by your own CView-derived class 
void CRenderView::SnapClient() 
{ 
 BeginWaitCursor();

 // Get client geometry 
 CRect rect; 
 GetClientRect(&rect); 
 CSize size(rect.Width(), rect.Height()); 
 TRACE("  client zone : (%d;%d)\n",size.cx,size.cy); 
 // Lines have to be 32 bytes aligned, suppose 24 bits per pixel 
 // I just cropped it 
 size.cx -= size.cx % 4; 
 TRACE("  final client zone : (%d;%d)\n", size.cx, size.cy);

 // Create a bitmap and select it in the device context 
 // Note that this will never be used ;-) but no matter 
 CBitmap bitmap; 
 CDC *pDC = GetDC(); 
 CDC MemDC; 
 ASSERT(MemDC.CreateCompatibleDC(NULL)); 
 ASSERT(bitmap.CreateCompatibleBitmap(pDC, size.cx, size.cy)); 
 MemDC.SelectObject(&bitmap);

 // Alloc pixel bytes 
 int NbBytes = 3 * size.cx * size.cy; 
 unsigned char *pPixelData = new unsigned char[NbBytes];

 // Copy from OpenGL 
 ::glReadPixels(0, 0, size.cx, size.cy, GL_RGB,GL_UNSIGNED_BYTE, pPixelData);

 // Fill header 
 BITMAPINFOHEADER header; 
 header.biWidth  = size.cx; 
 header.biHeight = size.cy; 
 header.biSizeImage = NbBytes; 
 header.biSize   = 40; 
 header.biPlanes = 1; 
 header.biBitCount =  3 * 8; // RGB 
 header.biCompression = 0; 
 header.biXPelsPerMeter = 0; 
 header.biYPelsPerMeter = 0; 
 header.biClrUsed = 0; 
 header.biClrImportant = 0;

 // Generate handle 
 HANDLE handle = (HANDLE)::GlobalAlloc (GHND,sizeof(BITMAPINFOHEADER) + NbBytes); 
 if(handle != NULL) 
 { 
  // Lock handle 
  char *pData = (char *) ::GlobalLock((HGLOBAL)handle); 
  // Copy header and data 
  memcpy(pData,&header,sizeof(BITMAPINFOHEADER)); 
  memcpy(pData+sizeof(BITMAPINFOHEADER),pPixelData,NbBytes); 
  // Unlock 
  ::GlobalUnlock((HGLOBAL)handle);

  // Push DIB in clipboard 
  OpenClipboard(); 
  EmptyClipboard(); 
  SetClipboardData(CF_DIB,handle); 
  CloseClipboard(); 
 }

 // Cleanup 
 MemDC.DeleteDC(); 
 bitmap.DeleteObject(); 
 delete [] pPixelData;

 EndWaitCursor(); 
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值