Removing HBITMAP results in runtime access violation

I have the following code to take a screenshot from a window and get the color of a specific pixel in it:

void ProcessScreenshot(HWND hwnd){

HDC WinDC;
HDC CopyDC;
HBITMAP hBitmap;
RECT rt;

GetClientRect (hwnd, &rt);
WinDC = GetDC (hwnd);
CopyDC = CreateCompatibleDC (WinDC);

//Create a bitmap compatible with the DC
hBitmap = CreateCompatibleBitmap (WinDC,
    rt.right - rt.left, //width
    rt.bottom - rt.top);//height

SelectObject (CopyDC, hBitmap);

BitBlt (CopyDC,   //destination
    0,0,
    rt.right - rt.left, //width
    rt.bottom - rt.top, //height
    WinDC,    //source
    0, 0,
    SRCCOPY);       

COLORREF col = ::GetPixel(CopyDC,145,293);

// Do some stuff with the pixel colour.... 

delete hBitmap;

ReleaseDC(hwnd, WinDC);
ReleaseDC(hwnd, CopyDC);

}

string 'delete hBitmap;' raises a runtime error: access violation. Think I can't just delete it like that?

Since bitmaps take up a lot of space, if I don't get rid of it, I get a huge memory leak. My question is: Does DC exempt HBITMAP from this, or does it stick even after I released DC? If so, how to get rid of HBITMAP?

+3
source share
2 answers

GDI DeleteObject, delete. , new.

+8

delete , new.

HBITMAP - -, GDI DeleteObject.

, SelectObject, SelectObject, , DeleteObject. , , , .

+3

Source: https://habr.com/ru/post/1737862/


All Articles