Button按钮控件自绘操作
程序员文章站
2022-05-28 14:33:46
...
1、首先为工程CButton类的派生类CMyButton,在CMyButton的头文件中添加一个用于保存图标的成员变量和一个设置函数:用来为按钮加载我们导入的图标。
public:
HICON m_hIcon;
void SetIcon(UINT nIcon)
{
m_hIcon = AfxGetApp()->LoadIcon(nIcon);
}
//......
2、在CMyButton.cpp中重写虚函数:virtual void DrawItem(LPDRAWITEMSTRUCT lpDIS);
void CMyButton::DrawItem(LPDRAWITEMSTRUCT lpDIS)
{
CDC *dc;
//将句柄转换为CDC类的对象,以下两种方法都可以
dc = CDC::FromHandle(lpDIS->hDC);
//dc.Attach(lpDIS->hDC);
//获取按钮的矩形区域
CRect RtBtn = lpDIS->rcItem;
dc->FillSolidRect(RtBtn,RGB(100,50,100));
//如果按钮的状态为选中,矩形框向右下方移动
if (lpDIS->itemState & ODS_SELECTED)
{
RtBtn.OffsetRect(1,1);
}
//画出自定义图标到按钮上
CRect RtIcon = RtBtn;
RtIcon.top = (RtIcon.Height()-16)/2;
RtIcon.left = RtIcon.left + 5;
dc->SetBkMode(TRANSPARENT);
DrawIconEx(lpDIS->hDC,RtIcon.left,RtIcon.top,m_hIcon,16,16,0,NULL,DI_NORMAL);
//dc.DrawIcon(RtIcon.left,RtIcon.top,m_hIcon);
CRect RtText;
RtText.CopyRect(RtBtn);
CString strText;
GetWindowText(strText);
//向右平移文字
RtText.left += 20;
dc->SetTextColor(GetSysColor(COLOR_WINDOWTEXT));
dc->DrawText(strText,RtText,DT_CENTER|DT_VCENTER|DT_SINGLELINE);
//画按钮的边框
if (lpDIS->itemState & ODS_SELECTED)
{
dc->DrawEdge(&RtBtn,BDR_SUNKENINNER,BF_RECT);
}else{
dc->DrawEdge(&RtBtn,BDR_RAISEDOUTER,BF_RECT);
}
//模拟当按钮有焦点时画虚线到按钮上
CRect RtFocus;
if (lpDIS->itemState & ODS_FOCUS)
{
RtFocus.CopyRect(RtBtn);
RtFocus.DeflateRect(2,2);
dc->DrawFocusRect(RtFocus);
}
//dc.Detach();//和Attach成对使用
}
3、将按钮的属性Owner Draw设置为TRUE。并为3个绑定控件变量,类型为:CMyButton
CMyButton m_Btn1;
CMyButton m_Btn2;
CMyButton m_Btn3;
4、在程序的初始化函数中使用我们自己封装的SetIcon()函数加载我们事先导入的3个图标:
BOOL CListSortDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
m_Btn1.SetIcon(IDI_ICON1);
m_Btn2.SetIcon(IDI_ICON2);
m_Btn3.SetIcon(IDI_ICON4);
//......
上一篇: Java 类型擦除