This test capturing the Desktop as HBITMAP and saving it as PNG with WIC works for me (Windows 10 22H2) :
(all the if (SUCCEEDED(hr)) have to be replaced by your TRY_HRESULT()...)
IWICImagingFactory* m_pImagingFactory = NULL;
HRESULT hrInit = CoInitialize(NULL);
HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&m_pImagingFactory));
if (SUCCEEDED(hr))
{
HDC hDC = GetDC(NULL);
HDC hDCMem = CreateCompatibleDC(hDC);
int nImageWidth = GetSystemMetrics(SM_CXSCREEN);
int nImageHeight = GetSystemMetrics(SM_CYSCREEN);
HBITMAP hBitmap = CreateCompatibleBitmap(hDC, nImageWidth, nImageHeight);
HBITMAP hBitmapOld = (HBITMAP)SelectObject(hDCMem, hBitmap);
BitBlt(hDCMem, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), hDC, 0, 0, SRCCOPY);
IWICBitmap* pWICBitmap;
hr = m_pImagingFactory->CreateBitmapFromHBITMAP(hBitmap, NULL, WICBitmapUseAlpha, &pWICBitmap);
if (SUCCEEDED(hr))
{
IWICBitmapEncoder* pEncoder;
hr = m_pImagingFactory->CreateEncoder(GUID_ContainerFormatPng, NULL, &pEncoder);
if (SUCCEEDED(hr))
{
IWICStream* spStream = NULL;
hr = m_pImagingFactory->CreateStream(&spStream);
if (SUCCEEDED(hr))
{
hr = spStream->InitializeFromFilename(L"capture.png", GENERIC_WRITE);
}
if (SUCCEEDED(hr))
{
hr = pEncoder->Initialize(spStream, WICBitmapEncoderNoCache);
IWICBitmapFrameEncode* spFrame = NULL;
if (SUCCEEDED(hr))
{
hr = pEncoder->CreateNewFrame(&spFrame, NULL);
if (SUCCEEDED(hr))
{
hr = spFrame->Initialize(NULL);
if (SUCCEEDED(hr))
{
hr = spFrame->SetSize(nImageWidth, nImageHeight);
WICPixelFormatGUID format;
pWICBitmap->GetPixelFormat(&format);
if (SUCCEEDED(hr))
{
hr = spFrame->SetPixelFormat(&format);
if (SUCCEEDED(hr))
{
hr = spFrame->WriteSource(pWICBitmap, NULL);
if (SUCCEEDED(hr))
{
hr = spFrame->Commit();
if (SUCCEEDED(hr))
{
hr = pEncoder->Commit();
}
}
}
}
}
}
}
}
}
}
SelectObject(hDCMem, hBitmapOld);
DeleteObject(hDCMem);
DeleteObject(hBitmap);
ReleaseDC(NULL, hDC);
}