VC realize the transparent windows

但是有个函数可以轻松实现,就是SetLayeredWindowAttributes, 运用这个函数便可轻松实现窗口透明效果。

简单介绍一下SetLayeredWindowAttributes,详见msdn。

BOOL SetLayeredWindowAttributes(
HWND hwnd, // handle to the layered window
COLORREF crKey, // specifies the color key
BYTE bAlpha, // value for the blend function
DWORD dwFlags // action
);

Windows NT/2000/XP: Included in Windows 2000 and later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

其中dwFlags有LWA_ALPHA和LWA_COLORKEY。LWA_ALPHA被设置的话,通过bAlpha决定透明度,LWA_COLORKEY被设置的话,则指定被透明掉的颜色为crKey,其他颜色则正常显示。

注意:要使使窗体拥有透明效果,首先要有WS_EX_LAYERED扩展属性。

实现代码:

SetWindowLong(this->GetSafeHwnd(),GWL_EXSTYLE,
GetWindowLong(this->GetSafeHwnd(),GWL_EXSTYLE)^0×80000);
HINSTANCE hInst = LoadLibrary(“User32.DLL”);
if(hInst)
{
typedef BOOL (WINAPI *MYFUNC)(HWND,COLORREF,BYTE,DWORD);
MYFUNC fun = NULL;
//取得SetLayeredWindowAttributes函数指针
fun=(MYFUNC)GetProcAddress(hInst, “SetLayeredWindowAttributes”);
if(fun)fun(this->GetSafeHwnd(),0,128,2);
FreeLibrary(hInst);
}

上面的一段代码加入到OnInitDialog()函数中,便可初始化窗口为半透明了,若想改变透明度,只要修改第三个参数便可,范围为0~255。

原文地址:https://www.cnblogs.com/CBDoctor/p/2839949.html