我希望在桌面上创建一个透明窗口。
为此,我创建了具有桌面背景的HDC(创建了桌面的HBITMAP并将其应用于我的HDC),并调用了UpdateLayeredWindow。
到现在为止还挺好。
对于性能问题,我需要保留一个持久的GDI +对象,这意味着我的HDC和HBITMAP需要在绘画之间保持相同的句柄(假设桌面DC不变),与this question相同。
在第一次绘画迭代中,一切顺利。在第二次绘画迭代中,由于HDC和HBITMAP不变,因此我在现有的HDC上重新绘画,这意味着我得到了双重图像(背景不会被擦除)。
这是我正在做的代码示例:
bool SomeUI::Draw()
{
BLENDFUNCTION blend = {0};
POINT ptPos = {0};
SIZE sizeWnd = {0};
POINT ptSrc = {0};
BOOL bUpdate = FALSE;
// Get the client rect
RECT rctWindow;
bool bGot = GetWindowRect(rctWindow);
if (!bGot)
return false;
// Get the desktop's device context
HDC hDCDesktop = GetDC(NULL);
if (!hDCDesktop)
return false;
int nWidth = abs(rctWindow.right - rctWindow.left);
int nHeight = abs(rctWindow.bottom - rctWindow.top);
// Create 32Bit bitmap to apply PNG transparency
VOID *ppvBits = NULL;
BITMAPINFO BitmapInfo = {0};
BitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
BitmapInfo.bmiHeader.biWidth = nWidth;
BitmapInfo.bmiHeader.biHeight = nHeight;
BitmapInfo.bmiHeader.biPlanes = 1;
BitmapInfo.bmiHeader.biBitCount = 32;
BitmapInfo.bmiHeader.biCompression = BI_RGB;
HBITMAP hBmp = CreateDIBSection(hDCDesktop, &BitmapInfo, DIB_RGB_COLORS, &ppvBits, NULL, 0);
if (!hBmp || hBmp==(HBITMAP)ERROR_INVALID_PARAMETER)
goto releaseHandles;
// Create a compatible DC and select the newly created bitmap
if (!m_hDC)
{
m_hDC = CreateCompatibleDC(hDCDesktop);
if (!m_hDC)
goto releaseHandles;
SelectObject(m_hDC, hBmp);
}
else
{
///////////////////////////////////////////////////////////////////////
//
// The problem lies here, this is where I need to reset the HBITMAP
// according to the desktop here (to have a transparent DC to work on)
//
///////////////////////////////////////////////////////////////////////
}
// The drawing logic
bool bInnerDraw = Draw(m_hDC);
if (!bInnerDraw)
goto releaseHandles;
// Call UpdateLayeredWindow
blend.BlendOp = AC_SRC_OVER;
blend.SourceConstantAlpha = 255;
blend.AlphaFormat = AC_SRC_ALPHA;
sizeWnd.cx = nWidth;
sizeWnd.cy = nHeight;
ptPos.x = rctWindow.left;
ptPos.y = rctWindow.top;
bUpdate = UpdateLayeredWindow(m_hWnd, hDCDesktop, &ptPos, &sizeWnd, m_hDC, &ptSrc, 0, &blend, ULW_ALPHA);
if (!bUpdate)
goto releaseHandles;
releaseHandles:
// releasing handles
}
有任何想法吗?
最佳答案
找到答案:
为了重置持久性HBITMAP(提醒:它需要保持相同的句柄),我们将将该区域的桌面背景设置为临时HBITMAP,并将其复制到持久性HBITMAP。
为了实现这一目标(从一个HBITMAP复制到另一个HBITMAP),我们将创建一个临时HDC并选择一个临时HBITMAP,然后将临时HDC复制到持久性HDC(使用BitBlt)
这是代码:
hBmpTemp = CreateDIBSection(hDCDesktop, &BitmapInfo, DIB_RGB_COLORS, &ppvBits, NULL, 0);
if (!hBmpTemp || hBmpTemp==(HBITMAP)ERROR_INVALID_PARAMETER)
goto releaseHandles;
HDC hTempDC = CreateCompatibleDC(NULL);
if (!hTempDC)
goto releaseHandles;
SelectObject(hTempDC, hBmpTemp);
::BitBlt(m_hPersistentDC, 0, 0, nWidth, nHeight, hTempDC, rctWindow.left, rctWindow.top, SRCCOPY);
::DeleteDC(hTempDC);
关于c++ - 将现有的HBITMAP重置为桌面背景(Win32),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8377525/