首先,用生成向导建立个基于对话框的程序框架,取名为PartTransparent
第二,重写BOOL CPartTransparentDlg::OnInitDialog(),也就是重写,对话框类的OnInitDialog()这个函数,在里面,return TRUE;前面加入下面的代码:
SetWindowLong(this->GetSafeHwnd(),GWL_EXSTYLE,GetWindowLong(this->GetSafeHwnd(),GWL_EXSTYLE)^0x80000);
HINSTANCE hInst = LoadLibrary(L"User32.DLL");
if (hInst)
{
typedef BOOL (WINAPI * MYFUNC)(HWND,COLORREF,BYTE,DWORD);
MYFUNC fun = NULL;
fun = (MYFUNC)GetProcAddress(hInst,"SetLayeredWindowAttributes");
if (fun)
fun(this->GetSafeHwnd(),0,128,2);
FreeLibrary(hInst);
}
其中fun(this->GetSafeHwnd(),0,128,2);修改窗口的透明度,值越接近255越不透明。
方法二:
BOOL CALLBACK EnumChildFunc(HWND hwnd, LPARAM lParam)
{
CRgn *pRgn = (CRgn*)lParam;
CRect rcChild;
::GetWindowRect(hwnd, rcChild);
CRgn rgnChild;
CRgn rgnCopy;
rgnCopy.CreateRectRgn(0, 0, 1, 1);
rgnCopy.CopyRgn(pRgn);
rgnChild.CreateRectRgn(rcChild.left, rcChild.top,
rcChild.right, rcChild.bottom);
pRgn-> CombineRgn(&rgnCopy, &rgnChild, RGN_OR);
return TRUE;
}
int SetBackTransparent(CWnd *pWnd, BOOL bClientOnly = TRUE)
{
CRgn rgn;
if(bClientOnly)
{
CRgn rgnWindow, rgnClient;
CRect rcWindow, rcClient, rcRgn;
pWnd-> GetWindowRect(rcWindow);
pWnd-> GetClientRect(rcClient);
pWnd-> ClientToScreen(rcClient);
rgnWindow.CreateRectRgn(rcWindow.left, rcWindow.top,
rcWindow.right, rcWindow.bottom);
rgnClient.CreateRectRgn(rcClient.left, rcClient.top,
rcClient.right, rcClient.bottom);
rgn.CreateRectRgn(0, 0, 1, 1);
rgn.CombineRgn(&rgnWindow, &rgnClient, RGN_DIFF);
}
else
{
rgn.CreateRectRgn(0, 0, 0, 0);
}
::EnumChildWindows(pWnd-> GetSafeHwnd(), (WNDENUMPROC)EnumChildFunc,(LPARAM)&rgn);
return pWnd-> SetWindowRgn(rgn, TRUE);
}
调用办法:
在CYourDialog::OnInitDialog里加上
SetBackTransparent(this);
如果要连非客户区都透明,用
SetBackTransparent(this, FALSE);