WM_CTLCOLOR和OnCtlColor消息的用法
来自:https://blog.csdn.net/stephen1315/article/details/7575799?utm_medium=distribute.pc_relevant.none-task-blog-title-7&spm=1001.2101.3001.4242
WM_CTLCOLOR消息用来完成对EDIT、STATIC、BUTTON等控件设置背景和字体颜色,其用法如下:
1.首先在自己需要设置界面的对话框上点击右键-->建立类向导-->加入WM_CTLCOLOR消息-->自动生成OnCtlColor()函数,此函数可以对本对话框的控件的界面外观做修饰,用法如下:
将类向导产生的函数做如下修改:
HBRUSH CDialogColor::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC,pWnd, nCtlColor); // TODO: Change any attributes of theDC here //设置显示字体 CFont * cFont=new CFont; cFont->CreateFont(16,0,0,0,FW_SEMIBOLD,FALSE,FALSE,0, ANSI_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,DEFAULT_PITCH&FF_SWISS,"Arial"); //对特定的控件做修改 switch(nCtlColor) { case CTLCOLOR_STATIC: //对所有静态文本控件的设置 { pDC->SetBkMode(TRANSPARENT); //设置背景为透明 pDC->SetTextColor(RGB(255,255,0)); //设置字体颜色 pWnd->SetFont(cFont); //设置字体 HBRUSH B = CreateSolidBrush(RGB(125,125,255)); //创建画刷 return (HBRUSH) B; //返回画刷句柄 } case CTLCOLOR_EDIT: //对所有编辑框的设置 { pDC->SetBkMode(TRANSPARENT); pDC->SetTextColor(RGB(255,255,0)); pWnd->SetFont(cFont); HBRUSH B = CreateSolidBrush(RGB(125,125,255)); return (HBRUSH) B; } default: return CDialog::OnCtlColor(pDC,pWnd, nCtlColor); } }
注:case的类别有以下几种:
CTLCOLOR_BTN 按钮控件
CTLCOLOR_DLG 对话框
CTLCOLOR_EDIT 编辑框
CTLCOLOR_LISTBOX 列表框
CTLCOLOR_MSGBOX 消息框
CTLCOLOR_SCROLLBAR 滚动条
CTLCOLOR_STATIC 静态文本
2.你可能觉得对所有的控件使用统一的界面设置觉得不自由,其实VC同样可以对特定的ID的控件进行设置,方法如下:
switch (pWnd->GetDlgCtrlID()) { //针对ID为IDC_CTL1、IDC_CTL2和IDC_CTL3的控件进行同样的设置 case IDC_CTL1: case IDC_CTL2: case IDC_CTL3: { pDC->SetBkMode(TRANSPARENT); pDC->SetTextColor(RGB(255,255, 0)); pWnd->SetFont(cFont); HBRUSH B = CreateSolidBrush(RGB(125,125,255)); return (HBRUSH) B; } default: return CDialog::OnCtlColor(pDC, pWnd, nCtlColor); }
通过消息WM_CTLCOLOR我们可以改变对话框或一些特殊控件的背景颜色 1、添加WM_CTLCOLOR消息映射。 2、在CWnd::OnCtlColor里面作相应的处理 HRESULT CWnd::OnCtlColor(CDC *pDC, CWnd *pWnd, UINT nCtlColor) { switch (nCtlColor) { case CTLCOLOR_BTN: // Button control { pDC->SetBkColor( RGB( 255, 0, 0) ); } break; case CTLCOLOR_DLG: // Dialog box break; case CTLCOLOR_EDIT: // Edit control { COLORREF bkColor = RGB(255,0,0); CRect rect; pWnd->GetClientRect(&rect); CBrush br; br.CreateSolidBrush(bkColor); pDC->FillRect(rect, &br);*/ pDC->SetBkColor(bkColor); } break; case CTLCOLOR_LISTBOX: // List-box control break; case CTLCOLOR_MSGBOX: // Message box break; case CTLCOLOR_SCROLLBAR: // Scroll-bar control break; case CTLCOLOR_STATIC: // Static control break; default: break; } return CWnd::OnCtlColor(pDC, pWnd, nCtlColor); }