头文件
#pragma once
// CJBoolControl
class CJBoolControl : public CButton
{
DECLARE_DYNAMIC(CJBoolControl)
public:
CJBoolControl();
virtual ~CJBoolControl();
void SetFasle();
void SetTrue();
bool Attach(const UINT nID,CWnd *nParant);
protected:
DECLARE_MESSAGE_MAP()
//virtual void DrawItem(LPDRAWITEMSTRUCT );
public:
virtual void DrawItem(LPDRAWITEMSTRUCT /*lpDrawItemStruct*/);
private:
COLORREF m_RedColor;
COLORREF m_GreenColor;
BOOL bstate;
CBrush brush;
public:
afx_msg void OnBnClicked();
};
源文件
// JBoolControl.cpp : 实现文件
//
#include "stdafx.h"
#include "BoolControl.h"
#include "JBoolControl.h"
// CJBoolControl
IMPLEMENT_DYNAMIC(CJBoolControl, CButton)
CJBoolControl::CJBoolControl()
{
m_RedColor = RGB(255,0,0);
m_GreenColor = RGB(0,255,0);
bstate = FALSE;
brush.CreateSolidBrush(m_GreenColor);
}
CJBoolControl::~CJBoolControl()
{
}
BEGIN_MESSAGE_MAP(CJBoolControl, CButton)
ON_CONTROL_REFLECT(BN_CLICKED, &CJBoolControl::OnBnClicked)
END_MESSAGE_MAP()
bool CJBoolControl::Attach(const UINT nID,CWnd *pParant)
{
if (SubclassDlgItem(nID,pParant))
{
return false;
}
else
return true;
}
void CJBoolControl::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
// TODO: 添加您的代码以绘制指定项
CDC dc;
dc.Attach(lpDrawItemStruct->hDC);//得到绘制的设备环境CDC
VERIFY(lpDrawItemStruct->CtlType==ODT_BUTTON);
const int bufSize = 512;
TCHAR buffer[215];
GetWindowText(buffer, bufSize);
USES_CONVERSION;
int size=strlen(W2A(buffer));//得到长度
SetBkMode(lpDrawItemStruct->hDC,TRANSPARENT);//透明
dc.FillRect(&(lpDrawItemStruct->rcItem),&brush);//
DrawText(lpDrawItemStruct->hDC,buffer,size,&lpDrawItemStruct->rcItem,DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_TABSTOP);
}
void CJBoolControl::OnBnClicked()
{
// TODO: 在此添加控件通知处理程序代码
bstate = !bstate;
if (bstate)
{
brush.DeleteObject();
brush.CreateSolidBrush(m_RedColor);
}
else
{
brush.DeleteObject();
brush.CreateSolidBrush(m_GreenColor);
}
this->Invalidate();
}
void CJBoolControl::SetFasle()
{
if (!bstate)
{
brush.DeleteObject();
brush.CreateSolidBrush(m_RedColor);
this->Invalidate();
bstate = !bstate;
}
}
void CJBoolControl::SetTrue()
{
if (bstate)
{
brush.DeleteObject();
brush.CreateSolidBrush(m_GreenColor);
this->Invalidate();
bstate = !bstate;
}
}
使用方法:
在 BOOL CBoolControlDlg::OnInitDialog()初始化
GetDlgItem(IDC_BUTTON1)->ModifyStyle(0,BS_OWNERDRAW,0);
m_button.Attach(IDC_BUTTON1,this);
实例代码:
https://download.youkuaiyun.com/download/u010261063/10294882
参考资料: