Issues with Screen Capture

I am a rank beginner at Windows programming, having never done anything at all before this project, so forgive me for any silly mistakes.

I am trying to capture the contents of specific open windows in order to search the image for certain characters/symbols. Below is what I have so far from modifying snippets I've found through google.

1. Sometimes the image is captured before the window is brought to the foreground, or even during and I get a weird translucent overlay of the background. How do I make sure the window is fully on the foreground before the screen capture?
2. The code does what I expect, except the image has unwanted margins. I do not want to see any part of the background, just the client area of the window.
3. Is my approach even reasonable for the task I want to accomplish, or is this way off base?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <windows.h>

using namespace std;

BOOL CALLBACK EnumWindowsProc(HWND, LPARAM);
void screenshot(HWND);

int main()
{
    EnumWindows(EnumWindowsProc, NULL);
}

BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
	char title[80];
	char className[80];
	GetWindowText(hwnd, title, sizeof(title));
	GetClassName(hwnd, className, sizeof(className));
        //C++.com just as an example
	if (string(title).find("C++ Forum") != string::npos && string(className) == "ApplicationFrameWindow")
    {
        cout << "Window title: " << title << '\n';
        cout << "Window class: " << className << '\n';
        screenshot(hwnd);
    }
	return TRUE;
}

void screenshot(HWND hwnd)
{
    SetForegroundWindow(hwnd);
    RECT rWindowRect;
    GetWindowRect(hwnd, &rWindowRect);
    // copy screen to bitmap
    HDC     hWindow = GetDC(NULL);
    HDC     hDC     = CreateCompatibleDC(hWindow);
    HBITMAP hBitmap = CreateCompatibleBitmap(hWindow, abs(rWindowRect.left-rWindowRect.right), abs(rWindowRect.top-rWindowRect.bottom));
    HGDIOBJ old_obj = SelectObject(hDC, hBitmap);
    BOOL    bRet    = BitBlt(hDC, 0, 0, abs(rWindowRect.left-rWindowRect.right), abs(rWindowRect.top-rWindowRect.bottom), hWindow, rWindowRect.left, rWindowRect.top, SRCCOPY);

    // save bitmap to clipboard for easy testing
    OpenClipboard(NULL);
    EmptyClipboard();
    SetClipboardData(CF_BITMAP, hBitmap);
    CloseClipboard();

    // clean up
    SelectObject(hDC, old_obj);
    DeleteDC(hDC);
    ReleaseDC(NULL, hWindow);
    DeleteObject(hBitmap);
}
The screenshot should be done withing the WM_DRAW event of the captured window. Thus you need to add your message handler function to the window. I never did this, but I would think it is possible.
Topic archived. No new replies allowed.