代码之家  ›  专栏  ›  技术社区  ›  Oliver

删除HBITMAP会在运行时导致访问冲突

  •  3
  • Oliver  · 技术社区  · 16 年前

    我有以下代码来截取一个窗口的屏幕截图,并获取其中特定像素的颜色:

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

    行“delete hBitmap;”导致运行时错误:访问冲突。我想我不能就这样删除它?

    因为位图占用了很多空间,如果我不把它处理掉,我最终会导致巨大的内存泄漏。我的问题是:发布DC-HBITMAP是为了解决这个问题,还是在我发布DC之后它仍然存在?如果是后者,我如何正确地摆脱HBITMAP?

    2 回复  |  直到 16 年前
        1
  •  8
  •   avakar    16 年前

    必须使用销毁GDI对象 DeleteObject 不 delete new .

        2
  •  3
  •   CB Bailey    16 年前

    delete new .

    HBITMAP 是位图句柄,需要使用GDI函数释放关联的对象 DeleteObject .

    SelectObject 选择对象 删除对象