Tips for Visual C ++: implement transparent forms
I. background
Everyone envy the transparency of flashget. Traditional Windows ApplicationsProgramTo achieve a translucent effect, you generally need to process the wm_paint message window of your own window, which is very troublesome. now, setlayeredwindowattributes is a new Windows API, which is supported by Win2000 and later versions. It can make the form transparent. I searched on Google to introduce the setlayered?wattributesArticleMostly in Delphi and VB. It was hard to find a VC article. After processing it according to law, the VC Ide said that my setlayered?wattributes is not defined! Later I thought that my SDK was not upgraded. So I searched the "*. H" file "setlayeredwindowattributes" in the VC installation directory. What should I do? Upgrade the SDK. I went to Microsoft's website to check that the new SDK has more than two hundred MB of core sdks (larger after decompression). Sorry, no partition on my hard disk is larger than MB! What should I do? When I was disappointed that such a fun API could not be used, I suddenly thought of the method of using undisclosed APIs. this is a system-supported API that your SDK does not have. Use it as an API that is not publicly available in windows!
Ii. Briefly introduce setlayeredwindowattributes: (See msdn for details)
Bool setlayeredwindowattributes (
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: supported ded in Windows 2000 and later.
Windows 95/98/me: unsupported.
Header: declared in winuser. h; Include windows. h.
Library: Use user32.lib.
Some constants:
Ws_ex_layered = 0x80000;
Lwa_alpha = 0x2;
Lwa_colorkey = 0x1
Dwflags contains lwa_alpha and lwa_colorkey. If lwa_alpha is set, balpha is used to determine the transparency. If lwa_colorkey is set, the transparent color is specified as the crkey, and other colors are displayed normally.
Note: To make the form transparent, you must first have the ws_ex_layered extension attribute (which is not available in the old SDK ).
Iii. ExampleCode:
Add oninitdialog:
// Add the ws_ex_layered extension attribute
Setwindowlong (this-> getsafehwnd (), gwl_exstyle,
Getwindowlong (this-> getsafehwnd (), gwl_exstyle) ^ 0x80000 );
Hinstance hinst = loadlibrary ("user32.dll ");
If (hinst)
{
Typedef bool (winapi * myfunc) (hwnd, colorref, byte, DWORD );
Myfunc fun = NULL;
// Get the setlayeredwindowattributes function pointer
Fun = (myfunc) getprocaddress (hinst, "setlayeredwindowattributes ");
If (fun) Fun (this-> getsafehwnd (), 0,128, 2 );
Freelibrary (hinst );
}