【发布时间】:2018-05-15 21:50:49
【问题描述】:
我希望程序(用 c++ 编写)从屏幕上读取像素,但我得到的响应似乎很混乱,变量 start 表示鼠标的位置。正确的方法是什么? 我使用了 GetPixel() 效果很好,但我需要一个完整的位图来提高效率。代码如下:
#include <Windows.h>
#include <iostream>
#include <math.h>
#include <stdio.h>
using namespace std;
int nScreenWidth;
int nScreenHeight;
HBITMAP GetScreenBmp(HDC hdc) {
HDC hCaptureDC = CreateCompatibleDC(hdc);
HBITMAP hBitmap = CreateCompatibleBitmap(hdc, nScreenWidth, nScreenHeight);
HGDIOBJ hOld = SelectObject(hCaptureDC, hBitmap);
BOOL bOK = BitBlt(hCaptureDC,0,0,nScreenWidth, nScreenHeight, hdc,0,0,SRCCOPY|CAPTUREBLT);
SelectObject(hCaptureDC, hOld); // always select the previously selected object once done
DeleteDC(hCaptureDC);
return hBitmap;
}
int main() {
nScreenWidth = GetSystemMetrics(SM_CXSCREEN);
nScreenHeight = GetSystemMetrics(SM_CYSCREEN);
HBITMAP hBitmap;
int times = 0;
while (!GetAsyncKeyState(VK_SPACE) && times<1000)
{
times++;
POINT p;
GetCursorPos(&p);
HDC hdc = GetDC(0);
hBitmap = GetScreenBmp(hdc);
BITMAPINFO MyBMInfo = {0};
MyBMInfo.bmiHeader.biSize = sizeof(MyBMInfo.bmiHeader);
if(0 == GetDIBits(hdc, hBitmap, 0, 0, NULL, &MyBMInfo, DIB_RGB_COLORS)) {
cout << "error" << endl;
}
BYTE* lpPixels = new BYTE[MyBMInfo.bmiHeader.biSizeImage];
MyBMInfo.bmiHeader.biCompression = BI_RGB;
if(0 == GetDIBits(hdc, hBitmap, 0, MyBMInfo.bmiHeader.biHeight, (LPVOID)lpPixels, &MyBMInfo, DIB_RGB_COLORS)) {
cout << "error2" << endl;
}
//**HERE** - position is wrong?
int start = (p.y*nScreenWidth+p.x)*4;
for(int i = start; i < start + 4; i+=4)
{
cout << "R:" << (int)lpPixels[i+2] << " G:" << (int)lpPixels[i+1] << " B:" << (int)lpPixels[i] << endl;
}
ReleaseDC(NULL, hdc);
delete[] lpPixels;
Sleep(1000);
}
DeleteObject(hBitmap);
return 0;
}
【问题讨论】:
-
“看起来很乱”是什么意思?你遇到了什么问题?
-
我给了你尝试的代码 - 我得到了错误的 RGB 值,这不是我现在鼠标下的值。
-
您可以在实际问题中尽可能明确地描述您的问题。 “凌乱”并没有削减它,您的代码也无法编译,它在某处缺少大括号。
-
@RetiredNinja 对不起,我没有经验 - 这是我在这里的第一篇文章,无论如何我修复了括号,它现在可以编译;)
-
与您的问题无关,在 C++ 中几乎不需要使用运算符
new或delete。请改用std::vector<BYTE>。
标签: c++ winapi bitmap screen capture