ID:【118】
类型:Demo
开发工具:VS2017
简介:重绘的CListBox,可以在列表中显示对应的颜色框。
效果:
头文件:
#pragma once
// CMyListBox
class CMyListBox : public CListBox
{
DECLARE_DYNAMIC(CMyListBox)
public:
CMyListBox();
virtual ~CMyListBox();
protected:
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);;
virtual void MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct);
DECLARE_MESSAGE_MAP()
};
源文件:
// CMyListBox.cpp: 实现文件
//
#include "pch.h"
#include "A1.h"
#include "CMyListBox.h"
// CMyListBox
IMPLEMENT_DYNAMIC(CMyListBox, CListBox)
CMyListBox::CMyListBox()
{
}
CMyListBox::~CMyListBox()
{
}
BEGIN_MESSAGE_MAP(CMyListBox, CListBox)
END_MESSAGE_MAP()
// CMyListBox 消息处理程序
void CMyListBox::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
// TODO: Add your code to draw the specified item
ASSERT(lpDrawItemStruct->CtlType == ODT_LISTBOX);
CString str;
LPCTSTR lpszText = (LPCTSTR)lpDrawItemStruct->itemData;
str = lpszText;
ASSERT(lpszText != NULL);
CDC dc;
dc.Attach(lpDrawItemStruct->hDC);
RECT rt = lpDrawItemStruct->rcItem;
CBrush brush;
RECT rectRt = { rt.left,rt.top,20,rt.bottom-2};
if (wcscmp(lpszText,_T("red"))==0)
{
CBrush brush(RGB(255,0,0));
dc.FillRect(&rectRt, &brush);
}
else if (wcscmp(lpszText, _T("green")) == 0)
{
CBrush brush(RGB(0, 255, 0));
dc.FillRect(&rectRt, &brush);
}
else if (wcscmp(lpszText, _T("blue")) == 0)
{
CBrush brush(RGB(0, 0, 255));
dc.FillRect(&rectRt, &brush);
}
else if (wcscmp(lpszText, _T("yellow")) == 0)
{
CBrush brush(RGB(255, 255, 0));
dc.FillRect(&rectRt, &brush);
}
else
{
CBrush brush(RGB(255, 255, 255));
RECT rectRt = { rt.left,rt.top,20,rt.bottom };
dc.FillRect(&rectRt, &brush);
}
// Save these value to restore them when done drawing.
COLORREF crOldTextColor = dc.GetTextColor();
COLORREF crOldBkColor = dc.GetBkColor();
RECT rectRt2 = { rt.left+25,rt.top,rt.right,rt.bottom };
if ((lpDrawItemStruct->itemAction | ODA_SELECT) &&
(lpDrawItemStruct->itemState & ODS_SELECTED))
{
dc.SetTextColor(::GetSysColor(COLOR_HIGHLIGHTTEXT));
dc.SetBkColor(::GetSysColor(COLOR_HIGHLIGHT));
dc.FillSolidRect(&rectRt2,
::GetSysColor(COLOR_HIGHLIGHT));
}
else
dc.FillSolidRect(&rectRt2, crOldBkColor);
dc.DrawText(
str,
wcslen(str),
&rectRt2,
DT_LEFT | DT_SINGLELINE | DT_VCENTER);
// Reset the background color and the text color back to their
// original values.
dc.SetTextColor(crOldTextColor);
dc.SetBkColor(crOldBkColor);
dc.Detach();
return;
}
void CMyListBox::MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct)
{
// TODO: Add your code to determine the size of specified item
lpMeasureItemStruct->itemHeight = ::GetSystemMetrics(SM_CYMENUCHECK);
return;
}
调用:
m_list.InsertString(0, _T("red"));
m_list.InsertString(1, _T("green"));
m_list.InsertString(2, _T("blue"));
m_list.InsertString(3, _T("yellow"));