Screenshot code gives unexpected error on call to GetDIBits

  c++, winapi, windows

I’m using some C code to take a screenshot of a window, translated directly from a PowerBuilder sample that works perfectly. Here’s the part up to where there’s a problem:

extern "C" __declspec(dllexport) BOOL __stdcall WindowScreenShot(const wchar_t* fileName, unsigned long x, unsigned long y,
    unsigned long width, unsigned long height)
{
    HWND ll_hWnd;
    HDC ll_hdc, ll_hdcMem;
    HBITMAP ll_hBitmap;
    HANDLE hDib = NULL, hFile = NULL;
    char* lpBitmap = NULL;
    BOOL lb_result, lb_ok = FALSE;
    BITMAPINFO lstr_Info;
    BITMAPFILEHEADER lstr_Header;
    int li_pixels;
    DWORD dwBmpSize, dwBytesWritten;

    // get handle to windows background
    ll_hWnd = GetDesktopWindow();

    // Get the device context of window and allocate memory
    ll_hdc = GetDC(ll_hWnd);
    ll_hdcMem = CreateCompatibleDC(ll_hdc);
    ll_hBitmap = CreateCompatibleBitmap(ll_hdc, width, height);

    if (ll_hBitmap != 0)
    {
        // Select an object into the specified device context
        SelectObject(ll_hdcMem, ll_hBitmap);
        // Copy the bitmap from the source to the destination
        lb_result = BitBlt(ll_hdcMem, 0, 0, width, height, ll_hdc, x, y, SRCCOPY);
        lstr_Info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
        // Get the bitmapinfo (THIS LINE IS FAILING CURRENTLY)
        if (GetDIBits(ll_hdcMem, ll_hBitmap, 0, height, NULL, &lstr_Info, DIB_RGB_COLORS) > 0)
        { ...

That last call to GetDIBits always fails with the only documented error that it can give, ERROR_INVALID_PARAMETER. Since this code is basically absolutely identical to the PowerBuilder code, in terms of the structures used and Windows APIs called, I just have no idea how to resolve it. I’ve also read the API docs carefully and it all looks like it should work.

Any bright ideas? Thanks.

Source: Windows Questions

LEAVE A COMMENT