Getting a Bitmap Object of a screenshot in VC++ - c++

I'm trying to write a program that grabs a screen shot of the current active window and then does some basic computer vision with the result. The current code I have is as follows:
RECT rc;
HWND hwnd = GetForegroundWindow(); //the window can't be min
if(hwnd == NULL) {
cerr << "it can't find any 'note' window" << endl;
system ("pause");
return 0;
}
GetClientRect(hwnd, &rc);
//create
HDC hdcScreen = GetDC(NULL);
HDC hdc = CreateCompatibleDC(hdcScreen);
HBITMAP hbmp = CreateCompatibleBitmap(hdcScreen, rc.right - rc.left, rc.bottom - rc.top);
SelectObject(hdc, hbmp);
//Print to memory hdc
PrintWindow(hwnd, hdc, PW_CLIENTONLY);
//Get the bitmap
BITMAP bm;
GetObject (hbmp, sizeof(bm), &bm);
//release
DeleteDC(hdc);
DeleteObject(hbmp);
ReleaseDC(NULL, hdcScreen);
After everything's said an done, bm.bmBits is NULL. This is especially strange because all of bm's other fields are correct. Obviously I can't do very much without bm.bmBits. Could anyone tell me what I'm doing wrong?
This code is mostly copied from the answer to another question, but in that code handle to a bitmap was never transferred into a BITMAP struct, but instead was used to add the bitmap to the clipboard. Since I want to process the screenshot immediately, I'd rather extract the data within the handle immediately and process it.

bm.bmBits is NULL because you don't own the memory referenced by the bitmap. You need to have the kernel copy them for you, using GetDIBits or the like.

Related

Convert PrintWindow to BitBlt to capture screenshot of a specific window

I have a C++ program to capture the screenshot of a specific window and save it using the following code
int main()
{
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
RECT rc;
HWND hwnd = FindWindow(NULL,TEXT("Window Title Here"));
if(hwnd == NULL)
{
cout<<"Can't Find Window";
return 0;
}
GetClientRect(hwnd,&rc);
HDC hdcscreen = GetDC(NULL);
HDC hdc = CreateCompatibleDC(hdcscreen);
HBITMAP hbmp = CreateCompatibleBitmap(hdcscreen,rc.right - rc.left,rc.bottom - rc.top);
SelectObject(hdc,hbmp);
PrintWindow(hwnd,hdc,NULL);
BitmapToJpg(hbmp,rc.right - rc.left,rc.bottom-rc.top); //Function to convert hbmp bitmap to jpg
DeleteDC(hdc);
DeleteObject(hbmp);
ReleaseDC(NULL,hdcscreen);
}
This code works for many of the windows, but for some of the windows, the output is a black image with correct width and height. On searching I found a solution to use BitBlt(). But I cannot figure out how to replace PrintWindow() with BitBlt() and output to a HBITMAP. Help Need
First, replace hdcscreen by hdcwnd, which you get with GetDC(hwnd) instead of GetDC(NULL). It probably won't change anything, but it is more adequate, even with PrintWindow().
Then, just replace :
PrintWindow(hwnd,hdc,NULL);
By :
BitBlt( hdc, 0, 0, rc.right - rc.left,rc.bottom-rc.top, hdcwnd, 0, 0, SRCCOPY );

Loading Windows screenshot into SFML Image

In C++ code, I need to take a screenshot of a given window, store the pixels in memory, and then load them into an SFML Image object. So far, I have a handle to the window I need to screenshot and can create an HBITMAP object of it:
HWND window = FindWindow(TEXT("WindowName"), NULL);
RECT rc;
GetClientRect(window , &rc);
HBITMAP hbmp;
HDC hdcScreen = GetDC(NULL);
HDC hdc = CreateCompatibleDC(hdcScreen);
hbmp = CreateCompatibleBitmap(hdcScreen,
rc.right - rc.left, rc.bottom - rc.top);
SelectObject(hdc, hbmp);
PrintWindow(window, hdc, PW_CLIENTONLY);
GetObject(hbmp, sizeof(BITMAP), bitmap);
Now to be honest, I'm not really much of a Windows guy and I don't understand what's really happening with this WinAPI stuff here, this is just some code I found online to get screenshots. What I need to do is get this into some type of standard format that I can pass into SFML's function:
sf::Image::loadFromMemory(const void * data, std::size_t size)
And preferably something that will also be easy to send over a socket connection later. How can I get a nice, non-Windows-specific format for my screenshot?

White Flicker after CombineRgn function

It seems the flickering is generated by the CombineRgn function, but I really have no idea why this happens, since i've never used regions that much I'm possibly missing some knowledge on the matter.
Some events in the program triggers the addition of little rectangles to the main region, here's the code that handles that:
HRGN ActualRegion = CreateRectRgn(0, 0, 0, 0);
GetWindowRgn(hwnd, ActualRegion);
HRGN AddedRect = CreateRectRgn(//long code that creates a rectangle)
CombineRgn(ActualRegion, ActualRegion, AddedRect, RGN_OR);
SetWindowRgn(hwnd, ActualRegion, FALSE);
InvalidateRect(hwnd, NULL, FALSE);
White Flickering appears only after the invalidation if new regions where combined to the main one.
Here's how I'm implementing double buffering in WM_PAINT:
PLEASE NOTE that on creation i'm enabling the DWM blur behind function with an invalid region (different from the Main one) which means that everything painted with BLACK_BRUSH will result in a 100% "invisible" portion of the program
RECT r; GetClientRect(hwnd, &r);
PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps);
HDC MemDc = CreateCompatibleDC(hdc);
HBITMAP hBmp = CreateCompatibleBitmap(hdc, r.right, r.bottom);
HBITMAP hOld = (HBITMAP)SelectObject(MemDc, hBmp);
//Making sure this dc is filled with "invisible" pixels to display
SelectObject(MemDc, GetStockObject(BLACK_BRUSH));
Rectangle(MemDc, //arbitrary values that matches the entire screen);
BitBlt(hdc, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), MemDc, 0, 0, SRCCOPY);
//clean-up
SelectObject(MemDc, hOld);
DeleteObject(hBmp);
DeleteDC(MemDc);
EndPaint(hwnd, &ps);
WM_ERASEBKGND obviously returns TRUE without further handling, the WNDCLASSEX instance of the window has a default BLACK_BRUSH as the hbrBackground field.
I also tried to intercept and return TRUE from WM_NCPAINT message.
I'm doing everything necessary to avoid intermediate drawcalls, everything handled inside the WM_PAINT uses a backbuffer, also i'd like to mention i'm not working with images/bitmaps. Everything is drawn with gdi/gdi+, and in no place i'm actually issuing a "white" redraw that may possibly cause said flicker. I'm a bit lost here
Is it something that i'm possibly missing ? I can't really understand what may be causing white flickering in this scenario
The problem is not the CombineRgn function but the SetWindowRgn function which you call before the system draws the window for the first time. If you call SetWindowRgn after the first draw, no flicker. Unfortunatelly I don't know why. So, a way to counter that is to set the window region after the first draw (take the code that sets window region from WM_CREATE and leave only the DwmEnableBlurBehindWindow):
static int stc = 0;
//in WM_PAINT after the EndPaint(hwnd, &ps); add
HRESULT lr = DefWindowProc(hwnd, message, wParam, lParam);
if( stc == 0 ){
OnlyOnce();
stc++;
}
return lr;
and the OnlyOnce:
void OnlyOnce(void){
int X_Screen = GetSystemMetrics(SM_CXSCREEN);
int Y_Screen = GetSystemMetrics(SM_CYSCREEN);
HRGN ActualRegion = CreateRectRgn(X_Screen - 100, Y_Screen - 100, X_Screen - 100 + 40, Y_Screen - 100 + 40);
SetWindowRgn(hWnd, ActualRegion, true);
return;
}

Get a window snapshot and crop it

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?
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(...)
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

CreateCompatibleDC() failure

I'm using win32 for 2D animation. My program so far loads an array of HBITMAP objects created from resource. The problem arises during animation when calling CreateCompatibleDC() from "OnUpdate()" in code below. AFTER MANY CALLS to the OnUpdate function, the HDC object is not created(possibly not allocated in memory). This causes unexpected results when DeleteDC() is called to delete the HDC object. Here is the update function code from main.cpp:
void OnUpdate(
HWND hwnd)
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd,&ps);
if(!hdc)
{
MessageBox(NULL, L"Failed to Create Compatible DC - 'hdc' in OnUpdate()", L"ALERT", MB_OK);
PostMessage(hwnd, WM_DESTROY, NULL, NULL);
}
HPALETTE hpalT = SelectPalette(hdc,hpal,FALSE);
BITMAP bm;
HDC hdcMem = CreateCompatibleDC(hdc);
if(!hdcMem)
{
MessageBox(NULL, L"Failed to CreateCompatibleDC - 'hdcMem' in OnUpdate()", L"ALERT", MB_OK);
PostMessage(hwnd, WM_DESTROY, NULL, NULL);
}
SelectBitmap(hdcMem, bkgMain);
GetObject(bkgMain, sizeof(bm), &bm);
BitBlt(backDC, 0, 0, bm.bmWidth, bm.bmHeight, hdcMem, 0, 0, SRCCOPY);
// Clean up.
if(!DeleteDC(hdcMem))
{
MessageBox(NULL, L"Failed to DeleteDC - 'hdcMem' in OnUpdate()", L"ALERT", MB_OK);
PostMessage(hwnd, WM_DESTROY, NULL, NULL);
}
SelectPalette(hdc,hpalT,FALSE);
EndPaint(hwnd,&ps);
}
What is SelectBitmap()?
If it's a wrapper/alias for SelectObject() then you're leaking a bitmap.
SelectBitmap(hdcMem, bkgMain);
You should select the old bitmap back into the DC before deleting it:
This function returns the previously selected object of the specified
type. An application should always replace a new object with the
original, default object after it has finished drawing with the new
object.
I had a similar problem and found it was caused by calling CreateCompatibleDC from WM_CREATE (before my main window was created). I found GetDC(hwnd) gave me a HDC for the main window, but it could not be used until WM_CREATE was finished. I relocated my code to WM_PAINT and my code worked well.