CComPtr解构函数导致读取访问冲突

时间:2019-05-23 18:31:36

标签: winapi com access-violation

我编写了以下C ++ / Win32程序,以jpeg格式保存屏幕截图。

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winuser.h>
#include <strsafe.h>
#include <objbase.h>
#include <combaseapi.h>
#include <wincodec.h>
#include <wincodecsdk.h>
#include <atlbase.h>


int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow)
{
    HRESULT hr = S_OK;
    CComPtr<IWICImagingFactory> pFactory;

    hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);

    if (SUCCEEDED(hr))
    {
        hr = CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pFactory));
    }

    DEVMODE d;

    if (EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &d))
    {

        HWND desktop = GetDesktopWindow();
        HDC desktopDC = GetDC(desktop);
        HDC captureDC = CreateCompatibleDC(desktopDC);
        HBITMAP hCaptureBitmap = CreateCompatibleBitmap(desktopDC, d.dmPelsWidth, d.dmPelsHeight);

        SelectObject(captureDC, hCaptureBitmap);

        BitBlt(captureDC, 0, 0, d.dmPelsWidth, d.dmPelsHeight, desktopDC, 0, 0, SRCCOPY | CAPTUREBLT);

        CComPtr<IWICBitmap> wicbitmap;
        CComPtr<IWICStream> stream;
        CComPtr<IWICBitmapEncoder> encoder;
        CComPtr<IWICBitmapFrameEncode> frame;

        hr = pFactory->CreateBitmapFromHBITMAP(hCaptureBitmap, NULL, WICBitmapIgnoreAlpha, &wicbitmap);

        if (SUCCEEDED(hr))
        {
            hr = pFactory->CreateStream(&stream);
        }

        if (SUCCEEDED(hr))
        {
            hr = stream->InitializeFromFilename(L"screenshot.jpg", GENERIC_WRITE);
        }

        if (SUCCEEDED(hr))
        {
            hr = pFactory->CreateEncoder(GUID_ContainerFormatJpeg, NULL, &encoder);
        }

        if (SUCCEEDED(hr))
        {
            hr = encoder->Initialize(stream, WICBitmapEncoderNoCache);
        }

        if (SUCCEEDED(hr))
        {
            hr = encoder->CreateNewFrame(&frame, NULL);
        }

        if (SUCCEEDED(hr))
        {
            hr = frame->Initialize(NULL);
        }

        if (SUCCEEDED(hr))
        {
            hr = frame->SetSize(d.dmPelsWidth, d.dmPelsHeight);
        }

        if (SUCCEEDED(hr))
        {
            GUID pixel_format = GUID_WICPixelFormat24bppRGB;
            hr = frame->SetPixelFormat(&pixel_format);
        }

        if (SUCCEEDED(hr))
        {
            hr = frame->WriteSource(wicbitmap, NULL);
        }

        if (SUCCEEDED(hr))
        {
            hr = frame->Commit();
        }

        if (SUCCEEDED(hr))
        {
            hr = encoder->Commit();
        }


        ReleaseDC(desktop, desktopDC);
        DeleteDC(captureDC);
        DeleteObject(hCaptureBitmap);


    }

    CoUninitialize();

    return 0;
}

但是,当wWinMain函数结束时,我收到每个CComPtr对象的读取访问冲突错误。我是Windows编程的新手,所以在这里我不知道自己在做什么错。

0 个答案:

没有答案