title: C++ screen capture - how to read the bitmap?
body: <p>I wanted the program (written in c++) to read the pixels from the screen, but the response I get seems to be messy, the variable <strong>start</strong> indicates the position of the mouse. What is the correct way to do it?
  I used the <strong>GetPixel()</strong> which worked fine, but I need a whole bitmap for the efficiency. Here is the code:</p>
  
  <pre><code>#include &lt;Windows.h&gt;
  #include &lt;iostream&gt;
  #include &lt;math.h&gt;
  #include &lt;stdio.h&gt;
  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) &amp;&amp; times&lt;1000)
      {
          times++;
  
          POINT p;
          GetCursorPos(&amp;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, &amp;MyBMInfo, DIB_RGB_COLORS)) {
              cout &lt;&lt; "error" &lt;&lt; endl;
          }
  
          BYTE* lpPixels = new BYTE[MyBMInfo.bmiHeader.biSizeImage];
  
          MyBMInfo.bmiHeader.biCompression = BI_RGB;
  
          if(0 == GetDIBits(hdc, hBitmap, 0, MyBMInfo.bmiHeader.biHeight, (LPVOID)lpPixels, &amp;MyBMInfo, DIB_RGB_COLORS)) {
              cout &lt;&lt; "error2" &lt;&lt; endl;
          }
          //**HERE** - position is wrong?
          int start = (p.y*nScreenWidth+p.x)*4;
          for(int i = start; i &lt; start + 4; i+=4)
          {
              cout &lt;&lt; "R:" &lt;&lt; (int)lpPixels[i+2] &lt;&lt; " G:" &lt;&lt; (int)lpPixels[i+1] &lt;&lt; " B:" &lt;&lt; (int)lpPixels[i] &lt;&lt; endl;
          }
  
          ReleaseDC(NULL, hdc);
          delete[] lpPixels;
  
          Sleep(1000);
      }
      DeleteObject(hBitmap);
  
      return 0;
  }
  </code></pre>