0

I have the following code working properly, it takes a snapshot of the active window on my app, puts it in a HBITMAP variable and saves it in a file. Now I would like to be able to crop the image and save only a portion of it according to given start coordinates and width/height.

An important point is that I have to save the window with the title bar, not just the client area, so it was easy to achieve with PrintWindow() rather than the BitBlt() approach.

I prefer a solution that will use PrintWindow(), because the BitBlt() approach doesn't take the title bar properly (unless you know the way of doing that).

The current code that works properly for the whole window is:

HWND hParentWindow = GetActiveWindow();

    RECT rc;
    GetWindowRect(hParentWindow, &rc);
    int width = rc.right - rc.left;
    int height = rc.bottom - rc.top;

    //create
    HDC hdcParent = GetDC(NULL);
    HDC hdc = CreateCompatibleDC(hdcParent);
    HBITMAP hBmp = CreateCompatibleBitmap(hdcParent, width, height);
    SelectObject(hdc, hBmp);

    //Print to memory hdc
    PrintWindow(hParentWindow, hdc, 0);

    //copy to clipboard
    OpenClipboard(NULL);
    EmptyClipboard();
    SetClipboardData(CF_BITMAP, hBmp);
    CloseClipboard();

    // Save it in a file:
    saveBitmap(ofn.lpstrFile, hBmp);

    //release
    DeleteDC(hdc);
    DeleteObject(hBmp);
    ReleaseDC(NULL, hdcParent);

How can I save the bitmap cropped?

StackHeapCollision
  • 1,743
  • 2
  • 12
  • 19

2 Answers2

0

Essentially do a BitBlt. Here is a thread discussing this issue with a solution that appears to be adequate for your needs here:

Crop function BitBlt(...)

Community
  • 1
  • 1
GlGuru
  • 756
  • 2
  • 10
  • 21
0
  • create another intermediate hdc
  • print the window to this intermediate hdc.
  • copy (bitblt) the rect you need from this hdc to your bitmap hdc
  • relase the intermediate hdc
vlad_tepesch
  • 6,681
  • 1
  • 38
  • 80