- 创建一个与屏幕大小相同的顶层窗口,并设置
WS_EX_LAYERED样式
- 调用
SetLayeredWindowAttributes,设置透明色为RGB(255,0,255)。
- 用透明颜色完全填充您的窗口
- 在矩形上方用另一种颜色绘制矩形
编辑:
这个函数使用UpdateLayeredWindow 来达到同样的效果。我还没有实际测试过它,但它编译正常:)
void DrawRectangleOnTransparent(HWND hWnd, const RECT& rc)
{
HDC hDC = GetDC(hWnd);
if (hDC)
{
RECT rcClient;
GetClientRect(hWnd, &rcClient);
BITMAPINFO bmi = { 0 };
bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biWidth = rcClient.right;
bmi.bmiHeader.biHeight = -rcClient.bottom;
LPVOID pBits;
HBITMAP hBmpSource = CreateDIBSection(hDC, &bmi, DIB_RGB_COLORS, &pBits, 0, 0);
if (hBmpSource)
{
HDC hDCSource = CreateCompatibleDC(hDC);
if (hDCSource)
{
// fill the background in red
HGDIOBJ hOldBmp = SelectObject(hDCSource, hBmpSource);
HBRUSH hBsh = CreateSolidBrush(RGB(0,0,255));
FillRect(hDCSource, &rcClient, hBsh);
DeleteObject(hBsh);
// draw the rectangle in black
HGDIOBJ hOldBsh = SelectObject(hDCSource, GetStockObject(NULL_BRUSH));
HGDIOBJ hOldPen = SelectObject(hDCSource, CreatePen(PS_SOLID, 2, RGB(0,0,0)));
Rectangle(hDCSource, rc.left, rc.top, rc.right, rc.bottom);
DeleteObject(SelectObject(hDCSource, hOldPen));
SelectObject(hDCSource, hOldBsh);
GdiFlush();
// fix up the alpha channel
DWORD* pPixel = reinterpret_cast<DWORD*>(pBits);
for (int y = 0; y < rcClient.bottom; y++)
{
for (int x = 0; x < rcClient.right; x++, pPixel++)
{
if ((*pPixel & 0x00ff0000) == 0x00ff0000)
*pPixel |= 0x01000000; // transparent
else
*pPixel |= 0xff000000; // solid
}
}
// Update the layered window
POINT pt = { 0 };
BLENDFUNCTION bf = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
UpdateLayeredWindow(hWnd, hDC, NULL, NULL, hDCSource, &pt, 0, &bf, ULW_ALPHA);
SelectObject(hDCSource, hOldBmp);
DeleteDC(hDCSource);
}
DeleteObject(hBmpSource);
}
ReleaseDC(hWnd, hDC);
}
}