复选框的绘制与按钮基本相同,因为复选框本质上还是按钮。与按钮稍有区别的地方是:复选框的状态需要手动维护。
我们可以定义一个名为m_nCheck 的成员变量,维护复选框状态。
主要代码如下:
LRESULT CCheckBoxEx::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
// TODO: Add your specialized code here and/or call the base class
if (message == BM_GETCHECK)
{
return m_nCheck ;
}
else if (message == BM_SETCHECK)
{
m_nCheck = int(wParam) ;
Invalidate();
return 0;
}
return CButton::WindowProc(message, wParam, lParam);
}
void CCheckBoxEx::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
if (!m_bLBtnDown)
{
m_bLBtnDown = TRUE ;
}
CButton::OnLButtonDown(nFlags, point);
}
void CCheckBoxEx::OnLButtonUp(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
if (m_bLBtnDown)
{
m_bLBtnDown = FALSE ;
CRect rcClient ;
GetClientRect(rcClient) ;
if (rcClient.PtInRect(point))
{
SetCheck(1 - m_nCheck) ;
}
}
CButton::OnLButtonUp(nFlags, point);
}
绘图代码可参照前面按钮控件的绘制,在DrawItem虚函数里进行。
效果图如下: