工程源码:http://download.csdn.net/detail/zzzili/4186684
/************************************************************ * 类名:CPngStatic * 作用:在vc dialog中使用picture控件显示png图片,并相应鼠标 * 消息,可做picture button使用 * 注意:如果有背景时,背景控件必须在pngButton控件之下(tab=1) * 原理:使用控件背景覆盖法实现png图片的重画和透明效果 *************************************************************/ #ifndef _PNGBUTTON_ZZZILI #define _PNGBUTTON_ZZZILI #include "stdafx.h" class CMyImage:public Image { public: CMyImage(UINT uID) { // 初始化 Image 成员变量 nativeImage = NULL; lastResult = InvalidParameter; // 查找图片资源 HINSTANCE hInst = GetModuleHandle(NULL); HRSRC hRsrc = FindResource(hInst, MAKEINTRESOURCE(uID), _T("PNG")); if (!hRsrc) { return; } // 加载资源并获取其指针 HGLOBAL hMemRsrc = LoadResource(hInst, hRsrc); BYTE * pMemRsrc = (BYTE *)LockResource(hMemRsrc); // 为流分配全局内存空间 size_t sizeRsrc = SizeofResource(hInst, hRsrc); HGLOBAL hMemStrm = GlobalAlloc(GMEM_FIXED, sizeRsrc); if (!hMemStrm) { return; } // 拷贝图片资源到全局内存空间中 BYTE * pMemStrm = (BYTE *)GlobalLock(hMemStrm); memcpy(pMemStrm, pMemRsrc, sizeRsrc); // 使用图片资源流构造 Image 对象 IStream * pStrm = NULL; CreateStreamOnHGlobal(hMemStrm, TRUE, &pStrm); lastResult = DllExports::GdipLoadImageFromStream(pStrm, &nativeImage); pStrm->Release(); } }; class CPngStatic : public CStatic { public: CPngStatic(); ~CPngStatic(); void SetInitPngPic(int id);//设置初始png图片 void SetClickDownPngPic(int id);//设置鼠标左键按下时png图片 void SetClickUpPngPic(int id);//设置鼠标左键松开时png图片 void SetMouseOnPngPic(int id);//设置鼠标在控件上时png图片 private: RECT rp,lp; CDC *parentCDC; CDC* pFgndMemDC; BOOL isGetBj; CString pngFile; RECT m_rect; RECT m_bjRect; Image *m_image; private: CDC* GetParentBkgnd(CWnd *pWnd, CPoint ptDrawStart, int nWidth,int nHeight); CDC* CreateMixDC(CDC* pParentMemDC, Image* image); void AlphaGradientDraw(CWnd* pWnd, CDC* pFgndMemDC, CDC* pBkgndMemDC,CPoint ptDrawStart, int nWidth, int nHeight, int nTransparence); private: Image *ClickDownImage; Image *ClickUpImage; Image *MouseOnImage; Image *InitImage; BOOL isMouseOnPic; BOOL isSetClickDownImage; BOOL isSetClickUpImage; BOOL isSetMouseOnImage; BOOL isSetInitImage; private: void SetBj(); void SetBitmap(Image *image); public: DECLARE_MESSAGE_MAP() afx_msg void OnPaint(); afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg void OnMouseLeave(); afx_msg void OnMouseMove(UINT nFlags, CPoint point); }; #endif