且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从窗口获取像素数据\像素缓冲区并提取RGB?

更新时间:2023-11-10 12:52:58

有两个选项:

首先,可以使用GetPixel 。我用了很多。它工作正常:

First, you can use GetPixel(). I used it a lot. It works fine:

COLORREF GetPixel(
  HDC hdc, 
  int nXPos, 
  int nYPos
); 

在我们的日子里,处理器甚至使用这个函数调用一个rect可能在某些情况下工作。

With our days processors picking up even a rect using this function may work in certain cases.

其次,您可以将屏幕的内容复制到位图中。之后你可以把它放在剪贴板,用你的代码处理等。核心功能是:

Second, you can copy contents of the screen into a bitmap. After that you can place it in clipboard, process with your code, etc. The core function there is:

BOOL BitBlt(
  _In_  HDC hdcDest,
  _In_  int nXDest,
  _In_  int nYDest,
  _In_  int nWidth,
  _In_  int nHeight,
  _In_  HDC hdcSrc,
  _In_  int nXSrc,
  _In_  int nYSrc,
  _In_  DWORD dwRop
);

如果需要,我可以发布更详细的摘要。

I can post more detailed snippet if this is needed.

// Pick up the DC.
HDC hDC = ::GetDC(m_control);

// Pick up the second DC.
HDC hDCMem = ::CreateCompatibleDC(hDC);

// Create the in memory bitmap.
HBITMAP hBitmap = ::CreateCompatibleBitmap(hDC, bmp_size_x, bmp_size_y);

// Put bitmat into the memory DC. This will make it functional.
HBITMAP hBmpOld = (HBITMAP)::SelectObject(hDCMem, hBitmap);

// Clear the background.
HBRUSH hBkgr = ::CreateSolidBrush(props.bkgr_brush);
RECT bitmap_rect = { 0, 0, bmp_size_x, bmp_size_y };
::FillRect(hDCMem, &bitmap_rect, hBkgr);
::DeleteObject(hBkgr);

// Do the job.
::BitBlt(hDCMem, margins_rect.left, margins_rect.top,
    size_to_copy_x, size_to_copy_y, hDC,
    screen_from_x, screen_from_y, SRCCOPY);