开发环境:VC6, a dialog based MFC application.
主界面:
为对话框添加WM_CTLCOLOR消息响应函数:
HBRUSH CDDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); if (pWnd->GetDlgCtrlID() == IDC_EDIT1) // 获取子窗口控件ID{//pDC->SetTextColor(RGB(255, 0, 0)); // 设置文字颜色::SendMessage(GetDlgItem(IDC_EDIT1)->GetSafeHwnd(), WM_KILLFOCUS, 0, 0); // 让其失去焦点,防止文字被选中//((CEdit*)pWnd)->SetSel(-1, 0); // 不选中任何内容,与上句效果相同pDC->SetBkMode(TRANSPARENT); // 设置背景透明return (HBRUSH)::GetStockObject(NULL_BRUSH);}return hbr;
}
运行效果:
看到了吧,打红圈的地方背景和文字颜色都透明了。
对话框加载背景图片的代码如下(为对话框添加WM_PAINT消息响应函数):
void CDDlg::OnPaint()
{if (IsIconic()){CPaintDC dc(this); // device context for paintingSendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);// Center icon in client rectangleint cxIcon = GetSystemMetrics(SM_CXICON);int cyIcon = GetSystemMetrics(SM_CYICON);CRect rect;GetClientRect(&rect);int x = (rect.Width() - cxIcon + 1) / 2;int y = (rect.Height() - cyIcon + 1) / 2;// Draw the icondc.DrawIcon(x, y, m_hIcon);}else{//CDialog::OnPaint(); //要禁止这个调用CPaintDC dc(this);// 用于绘制的设备上下文CBitmap bmp;if(bmp.LoadBitmap(IDB_BITMAP1) == FALSE)return;BITMAP bmpStruct;bmp.GetBitmap(&bmpStruct); // 为了获得图片大小CDC dcMemory;dcMemory.CreateCompatibleDC(&dc); //创建内存DCCBitmap *pOldBmp = dcMemory.SelectObject(&bmp);CRect rect;GetClientRect(rect);dc.StretchBlt(0, 0, rect.Width(), rect.Height(), &dcMemory, 0, 0, bmpStruct.bmWidth, bmpStruct.bmHeight, SRCCOPY);//dc.BitBlt(0, 0, rect.Width(), rect.Height(), &dcMemory, 0, 0, SRCCOPY);dcMemory.SelectObject(pOldBmp);}
}