1.窗口透明度
调节窗口透明度,先使用SetWindowLog函数给窗口加上WX_EX_LAYERED属性,再使用SetlayeredWindowAttributes指定窗口透明度。
//用于改变窗口的属性或在窗口的额外存储空间设置一个32位值
LONG SetWindowLong( HWND hWnd, //窗口句柄
int nIndex, //要设置哪种值/额外存储区的偏移
LONG dwNewLong); //具体设置的值
//设置窗口分层透明度
BOOL SetLayeredWindowAttributes( HWND hWnd, //窗口句柄
COLORREF crKey, //透明色
BYTE bAlpha, //透明度,0表示完全透明,255表示不透明
DWORD dwFlags); //透明方式
透明方式:LWA_COLORKEY - 表示窗口指定了透明色
LWA_ALPHA - 表示要调整透明度
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include "stdafx.h" 2 #include "02窗口透明.h" 3 #include "commctrl.h" 4 5 /* 6 * 调节窗体透明度可以先使用SetWindowLong为窗体加上WS_EX_LAYERED属性,再使用来SetLayeredWindowAttributes指定窗体的透明度。 7 */ 8 9 WCHAR dlgTitle[] = L"变透明度窗口"; 10 11 BOOL CALLBACK DlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) 12 { 13 const int INIT_TRANSPARENT = 200; //窗体初始透明度 14 static HBRUSH s_hBitmapBrush; //位图画刷 15 HBITMAP hBitmap = 0; 16 switch (message) 17 { 18 case WM_INITDIALOG: 19 SetWindowText(hDlg, dlgTitle); 20 hBitmap = (HBITMAP)LoadImage(NULL, L"005.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION); 21 if (NULL == hBitmap) 22 { 23 MessageBox(hDlg, L"fail to load image!", L"Error", MB_ICONERROR); 24 exit(0); 25 } 26 //创建位图画刷 27 s_hBitmapBrush = CreatePatternBrush(hBitmap); 28 //设置分层属性 29 SetWindowLong(hDlg, GWL_EXSTYLE, GetWindowLong(hDlg, GWL_EXSTYLE) | WS_EX_LAYERED); 30 //设置透明度 0 - completely transparent 255 - opaque 31 SetLayeredWindowAttributes(hDlg, 0, INIT_TRANSPARENT, LWA_ALPHA); 32 //设置滑动条变化范围 33 SendMessage(GetDlgItem(hDlg, IDC_SLIDER_TRANSPARENT), TBM_SETRANGE, (WPARAM)FALSE, MAKELONG(0, 255)); 34 //设置滑块初始位置 35 SendMessage(GetDlgItem(hDlg, IDC_SLIDER_TRANSPARENT), TBM_SETPOS, (WPARAM)TRUE, INIT_TRANSPARENT); 36 return FALSE; 37 38 case WM_COMMAND: 39 if (IDCANCEL == LOWORD(wParam)) 40 { 41 DeleteObject(s_hBitmapBrush); 42 EndDialog(hDlg, LOWORD(wParam)); 43 return FALSE; 44 } 45 break; 46 case WM_HSCROLL: 47 // 获取当前滑块位置 48 int nTransparent; 49 nTransparent = SendMessage(GetDlgItem(hDlg, IDC_SLIDER_TRANSPARENT), TBM_GETPOS, 0, 0); 50 // 设置新透明度 51 SetLayeredWindowAttributes(hDlg, 0, nTransparent, LWA_ALPHA); 52 break; 53 case WM_CTLCOLORDLG: //对话框背影 54 return (BOOL)s_hBitmapBrush; 55 } 56 return FALSE; 57 } 58 59 int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) 60 { 61 DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, DlgProc); 62 return 0; 63 }
运行结果: