头文件
主要声明
DECLARE_MESSAGE_MAP()
VOID OnPaint();
cpp文件
#include <gdiplus.h>
using namespace Gdiplus;
BEGIN_MESSAGE_MAP(animateWindow, CDialog)
ON_WM_PAINT()
END_MESSAGE_MAP()
void transparentWindow::OnPaint()
{
initTransparent();
CDialog::OnPaint();
}
//OnPaint只会响应一遍,设置了UpdateLayeredWindow之后就不响应了,不过如果只是做一个背景的话,不用响应OnPaint,
void transparentWindow::initTransparent()
{
if (0 == m_ImagePath.GetLength())
{
return;
}
DWORD dwExStyle = GetWindowLong(m_hWnd, GWL_EXSTYLE);
if ((dwExStyle & WS_EX_LAYERED) != WS_EX_LAYERED)
{
SetWindowLong(GetSafeHwnd(), GWL_EXSTYLE, dwExStyle | WS_EX_LAYERED);
//SetLayeredWindowAttributes(m_BkColor, 128, LWA_COLORKEY);
//SetLayeredWindowAttributes和UpdateLayeredWindow互斥,只能一个有效
}
Bitmap *_pImage = Bitmap::FromFile(m_ImagePath);
//Bitmap::FromFile返回的对象可以用DeleteObject释放掉
//透明度由PNG图片的Alpha通道决定
if (NULL == dcSrc)
{
dcSrc = new CDC();
//bmp = new CBitmap();
}
RECT rt;
GetClientRect(&rt);
CDC *pDCDst = GetDC();
dcSrc->CreateCompatibleDC(pDCDst);
//bmp->CreateCompatibleBitmap(pDCDst, rt.right, rt.bottom);
//dcSrc->SelectObject(&bmp);
Gdiplus::Color color;//默认black
HBITMAP hBitmap;
_pImage->GetHBITMAP(color, &hBitmap);
dcSrc->SelectObject(hBitmap);
BLENDFUNCTION _Blend;
_Blend.BlendOp = 0;
_Blend.BlendFlags = 0;
_Blend.AlphaFormat = 1;
_Blend.SourceConstantAlpha = 255;
//此时,鼠标会穿透窗体中Alpha值为0的区域
GetWindowRect(&rt);
CPoint wndPoint;
wndPoint.x = rt.left;
wndPoint.y = rt.top;
CPoint srcPoint;
srcPoint.x = 0;
srcPoint.y = 0;
CSize clientSize;
clientSize.cx = _pImage->GetWidth();
clientSize.cy = _pImage->GetHeight();
UpdateLayeredWindow(pDCDst, &wndPoint, &clientSize,
dcSrc, &srcPoint,
0, &_Blend, ULW_ALPHA);
//bmp->DeleteObject();
dcSrc->DeleteDC();
ReleaseDC(pDCDst);
}
void transparentWindow::SetBkImage(CString filePath)
{
m_ImagePath = filePath;
}
调用的时候需要提前调用SetBkImage一面OnPaint中找不到文件
效果如下