以下代码中的函数均为对话框消息响应函数或虚函数。
1.控件大小随窗口大小改变
void CclientDlg::OnSize(UINT nType, int cx, int cy)
{
if (cx == 0 || cy == 0)
{
return;
}
CDialog::OnSize(nType, cx, cy);
CWnd *pWnd = GetWindow(GW_CHILD);
while(pWnd)
{
CRect rc;
pWnd->GetWindowRect(rc);
ScreenToClient(&rc);
rc.left = rc.left * cx / m_rect.Width();
rc.right = rc.right * cx / m_rect.Width();
rc.top = rc.top * cy / m_rect.Height();
rc.bottom = rc.bottom * cy / m_rect.Height();
pWnd->MoveWindow(rc);
pWnd = pWnd->GetNextWindow();
}
m_rect.SetRect(0, 0, cx, cy);
}
m_rect为全局变量,在OnInitDialog()里初始化:GetClientRect(m_rect)
void CLogin::OnPaint()
{
CPaintDC dc(this);
CRect rc;
GetClientRect(&rc);
CDC dcMem;
dcMem.CreateCompatibleDC(&dc);
CBitmap bmpBackground;
bmpBackground.LoadBitmap(IDB_LOGINBG);
BITMAP bitmap;
bmpBackground.GetBitmap(&bitmap);
CBitmap* pbmpPri = dcMem.SelectObject(&bmpBackground);
dc.SetStretchBltMode(COLORONCOLOR);
dc.StretchBlt(0, 0, rc.Width(), rc.Height(), &dcMem,
0, 0,bitmap.bmWidth, bitmap.bmHeight, SRCCOPY);//图片拉伸到窗口大小
//dc.BitBlt(0, 0, rc.Width(), rc.Height(), &dcMem, 0, 0, SRCCOPY);//图片不拉伸
}
IDB_LOGINBG为bmp格式资源图
BOOL CLogin::OnInitDialog()
{
::SetWindowLong(m_hWnd, GWL_EXSTYLE, GetWindowLong(m_hWnd, GWL_EXSTYLE) | WS_EX_LAYERED);
::SetLayeredWindowAttributes( m_hWnd, RGB(0, 255, 0), 0, LWA_COLORKEY);
return TRUE;
}
RGB(0, 255, 0)为变透明的颜色,上述代码会将对话框所有绿色区域变成透明。LWA_COLORKEY为LWA_ALPHA时可以使整个窗口透明,并用第三个参数控制透明度。
HBRUSH CMessage::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
if(nCtlColor== CTLCOLOR_STATIC)//根据控件类型
//if (pWnd->GetDlgCtrlID() == IDC_TITLE)//根据控件ID
{
pDC->SetBkMode(TRANSPARENT);
pDC->SetTextColor(RGB(255,255,255));
return (HBRUSH)GetStockObject(NULL_BRUSH);
//return (HBRUSH)CreateSolidBrush(RGB(255, 255, 255));//设置背景颜色
}
HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);
return hbr;
}
控件背景为透明时,static控件内容改变会出现文字叠加现象,因此每次改变文字后都要用RedrawWindow(rect)来重新绘制控件区域。
void CVideoPlayer::OnLButtonDown(UINT nFlags, CPoint point)
{
PostMessage(WM_NCLBUTTONDOWN,HTCAPTION,MAKELPARAM(point.x,point.y));
CDialog::OnLButtonDown(nFlags, point);
}
BOOL CVideoPlayer::PreTranslateMessage(MSG* pMsg)
{
if(pMsg->message == WM_KEYDOWN)
{
if (pMsg->wParam==VK_ESCAPE || pMsg->wParam==VK_RETURN)
{
return TRUE;
}
}
if (pMsg->message == WM_SYSKEYDOWN && pMsg->wParam == VK_F4 )
{
return TRUE;
}
return CDialog::PreTranslateMessage(pMsg);
}
void CVideoPlayer::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
if (nSBCode == TB_THUMBPOSITION && pScrollBar == GetDlgItem(IDC_VIDEOSLIDER))
{
//nPos为要获得的值
}
CDialogEx::OnHScroll(nSBCode, nPos, pScrollBar);
}