定义一个掩码颜色:
const COLORREF maskColor = RGB(0, 0, 0); // 透明颜色
const COLORREF textColor = RGB(0, 255, 0); // 标签文本颜色
设置窗体的Topmost为True,测试发现在OnInitDialog中修改无效,在资源中修改的可以生效。
窗口初始化中添加(例如OnInitDialog中):
// 鼠标穿透要带WS_EX_TRANSPARENT,并且要设置窗口置顶
LONG lWindLong = GetWindowLong(this->GetSafeHwnd(), GWL_EXSTYLE);
::SetWindowLong(m_hWnd, GWL_EXSTYLE, lWindLong | WS_EX_TRANSPARENT | WS_EX_LAYERED | WS_EX_TOPMOST);
SetLayeredWindowAttributes(maskColor, 0, LWA_COLORKEY);
//::SetWindowPos(m_hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
添加消息映射:
ON_WM_CTLCOLOR()
ON_WM_ERASEBKGND()
HBRUSH CglassDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) {
HBRUSH hBrush = __super::OnCtlColor(pDC, pWnd, nCtlColor);
switch(pWnd->GetDlgCtrlID()) {
case IDC_STATIC:
pDC->SetBkMode(TRANSPARENT);
pDC->SetTextColor(textColor);
return (HBRUSH)GetStockObject(HOLLOW_BRUSH);
default:
break;
}
return hBrush;
}
BOOL CglassDlg::OnEraseBkgnd(CDC *pDC) {
CRect clientRect ;
GetClientRect(&clientRect) ;
pDC->FillSolidRect(clientRect, maskColor);
return FALSE ;
}
参考: