CreateCompatibleDC() failure - c++

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.

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 );

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

Getting a Bitmap Object of a screenshot in VC++

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.

How to debug code in WM_PAINT in c++?

I have the following code in the WM_PAINT message handler of the main window :
void BossController::paint ( HWND hwnd, HBITMAP skin )
{
PAINTSTRUCT ps;
HDC hdc;
hdc = BeginPaint ( hwnd, &ps );
HDC dcSkin = CreateCompatibleDC ( hdc ); // memory dc for skin
HDC hMemDc = CreateCompatibleDC ( hdc ); // memory dc for painting
HBITMAP hmemBmp = CreateCompatibleBitmap ( hdc, width, height ); // Create bitmap to draw on
HBITMAP hOldMemBmp = (HBITMAP)SelectObject ( hMemDc, hmemBmp ); // select memory bitmap in memory dc
HBITMAP hOldSkinBmp = (HBITMAP)SelectObject ( dcSkin, skin ); //select skin bitmap in skin memory dc
BitBlt ( hMemDc, 0, 0, width, height, dcSkin, 0, 0, SRCCOPY ); // Paint Skin on Memory DC
BitBlt ( hdc, 0, 0, width, height, hMemDc, 0, 0, SRCCOPY ); // Paint Skin on Window DC
DeleteObject ( hOldSkinBmp );
DeleteObject ( hOldMemBmp );
DeleteObject( hmemBmp );
DeleteDC ( hMemDc );
DeleteDC ( dcSkin );
EndPaint ( hwnd, &ps );
};
I will be painting text on the skin aswell, that's why I am BitBlt ing on memory DC with a memory bitmap, I have tried with straight painting(directly to hdc) as well, but none worked, and I am not sure how to debug it. The only thing I could check was to check the skin against NULL in LoadBitmap function's return value and also in the void BossController::paint ( HWND hwnd, HBITMAP skin ). And BitBlt's return value.
It always shows a rectangle with the background color I chose while creating the window. (window is a custom skinned one so, no title bar etc is there.
Can someone point out the errors if any or the potential pitfalls or maybe how to debug it ?
It looks like nobody ever answered this.
First off, I don't know what framework you're using, but there are normally a few checks before one starts painting. A typical paint handler begins something like:
RECT r;
if (GetUpdateRect(&r) == 0)
{
// Nothing to paint, exit function.
return 0;
}
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
if (hdc == 0)
{
// No display device context available, exit function.
return 0;
}
Second, I don't know what 'skin' is (an HBITMAP, but I don't know anything about how it was created, where it come from, what its dimensions and bit depth are).
Third, your cleanup is incorrect. Always call SelectObject to restore the previous selected bitmap, pen, brush, etc. Then call DeleteObject on whatever you created.
As for how to debug, if something's broken in a paint handler, you should always strip it to the bare minimum, verify functionality, and start adding in things until it breaks. In this case, I would replace all of your existing code with a simple filled rectangle in a weird color and see if that works. Then I'd do a BitBlt directly from the 'skin' bitmap on top of the funky color, and see if that works.
The most common errors with GDI programming are caused by things like using the wrong coordinates (e.g. Window coordinates instead of Client coordinates, or giving the wrong offset into your source in a BitBlt call), failure to correctly create resources (e.g. CreateCompatibleDC, then calling CreateCompatibleBitmap using the new DC, which results in a monochrome bitmap), or failure to properly clean up (e.g. the way you didn't select the old resources before disposing of your newly-created ones). It's also common to not even initiate a repaint correctly, such that your WM_PAINT handler isn't even getting hit. The first step is always a breakpoint to make sure your code is even executing!