#define WS_EX_LAYERED 0x00080000 #define WS_EX_TRANSPARENT 0x00000020L #define LWA_ALPHA 0x00000002 template <class T> class CTranspanrented { enum Styles { WIN_TRANSPARENT = WS_EX_LAYERED, WIN_CLICK_THRU = WS_EX_LAYERED | WS_EX_TRANSPARENT }; bool m_bSupported; typedef BOOL (__stdcall *PFUNCSETLAYEREDWINDOWATTR)(HWND, COLORREF, BYTE, DWORD); PFUNCSETLAYEREDWINDOWATTR m_pfSetLayeredWindowAttributes; BOOL SetLayered(Styles Style) { if (!m_bSupported) { ATLTRACE(_T("Your OS does not support the transparency\n")); return FALSE; } T* pT = static_cast<T*>(this); return pT->ModifyStyleEx(0, Style); } BOOL RemoveLayered(Styles Style) { T* pT = static_cast<T*>(this); return pT->ModifyStyleEx(Style, 0); } public: CTranspanrented() { HMODULE hUser32 = GetModuleHandle(_T("User32.dll")); if (hUser32) { m_pfSetLayeredWindowAttributes = (PFUNCSETLAYEREDWINDOWATTR)::GetProcAddress(hUser32, "SetLayeredWindowAttributes"); if (m_pfSetLayeredWindowAttributes) m_bSupported = true; else m_bSupported = false; } } BOOL SetLayered() { return SetLayered(WIN_TRANSPARENT); } BOOL RemoveLayered() { return RemoveLayered(WIN_TRANSPARENT); } BOOL SetTransparent( int iTransparenty = 50) { // Need an extended style WS_EX_LAYERED and WS_EX_TRANSPARENT to pass mouse clicks through the window if (SetLayered(WIN_CLICK_THRU)) { // Without this call the window will not be visible return MakeTransparent( iTransparenty ); } else return FALSE; } BOOL RemoveClickThru() { return RemoveLayered(WIN_CLICK_THRU); } // Sets the transparency of the window BOOL MakeTransparent(int nOpacity = 50) { if (m_bSupported) { ATLASSERT(m_pfSetLayeredWindowAttributes); T* pT = static_cast<T*>(this); return m_pfSetLayeredWindowAttributes(pT->m_hWnd, 0, nOpacity * 2.55, LWA_ALPHA); } return FALSE; } };
使用方法:
class CWnd : public CLayered<CFloatWnd>
{
LRESULT CWnd::OnInitDialog( UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/ )
{
SetTransparent( 100 );
}
}