使用MFC自带的控件listCtrl, 有时候发现表头太长了,想显示多行,网上找了很久,发现就那两个原创转过来转过去,关键还解决不了问题。本人菜鸡一个,也看不太懂,稀里糊涂的。
最后实现该功能。望大神门,多发原创的帖子,共同学习。
1、首先派生一个列表头(CHeaderCtrl)的类CHeaderCtrlEx,在重载虚函数drawItem函数中
void CHeaderCtrlEx::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
ASSERT(lpDrawItemStruct->CtlType == ODT_HEADER);
HDITEM hdi;
TCHAR lpBuffer[256];
hdi.mask = HDI_TEXT;
hdi.pszText = lpBuffer;
hdi.cchTextMax = 256;
GetItem(lpDrawItemStruct->itemID, &hdi);
CDC* pDC;
pDC = CDC::FromHandle(lpDrawItemStruct->hDC);
//THIS FONT IS ONLY FOR DRAWING AS LONG AS WE DON'T DO A SetFont(...)
pDC->SelectObject(GetStockObject(DEFAULT_GUI_FONT));
// Draw the button frame.
::DrawFrameControl(lpDrawItemStruct->hDC,
&lpDrawItemStruct->rcItem, DFC_BUTTON, DFCS_BUTTONPUSH);
UINT uFormat = DT_CENTER;
//DRAW THE TEXT
::DrawText(lpDrawItemStruct->hDC, lpBuffer, strlen((char*)lpBuffer),
&lpDrawItemStruct->rcItem, uFormat);
pDC->SelectStockObject(SYSTEM_FONT);
}
2、派生一个ClistCtrl 的派生类CListCtrlExt,
成员变量 CHeaderCtrlEx m_headerList;
CFont m_font;
重载消息(WM_CREATE)函数OnCreate, 此处主要设置表头文字类型。代码如下:
int CListCtrlExt::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CListCtrl::OnCreate(lpCreateStruct) == -1)
return -1;
// TODO: 在此添加您专用的创建代码
m_font.CreatePointFont(190, _T("宋体"));
CHeaderCtrl* pHeader = NULL;
pHeader = GetHeaderCtrl();
if (pHeader == NULL)
return 1;
VERIFY(m_headerList.SubclassWindow(pHeader->m_hWnd));
m_headerList.SetFont(&m_font);
return 0;
}
3、创建一个动态的listCtrl ,在合适的类中加入一个成员变量 listCtrl派生类的指针。CListCtrlExt* m_pListCtrl;
初始化如下:
BOOL CHeaderList::OnInitDialog()
{
CDialogEx::OnInitDialog();
CRect rc;
GetDlgItem(IDC_LISTSTATIC)->GetWindowRect(&rc);
GetClientRect(rc);
if (m_pListCtrl == NULL)
{
m_pListCtrl = new CListCtrlExt;
}
DWORD dwStyle = WS_TABSTOP | WS_CHILD | WS_BORDER | WS_VISIBLE | LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS;
m_pListCtrl->Create(dwStyle, rc, this, IDC_HEADERLIST);
m_pListCtrl->InsertColumn(0, _T("编号\\asad"), LVCFMT_LEFT, 50);
m_pListCtrl->InsertColumn(1, _T("语文\nasdac"), LVCFMT_LEFT, 50);
m_pListCtrl->InsertColumn(2, _T("数\n学"), LVCFMT_LEFT, 20);
m_pListCtrl->InsertColumn(3, _T("地\n理"), LVCFMT_LEFT, 20);
m_pListCtrl->InsertColumn(4, _T("英语\n分数"), LVCFMT_LEFT, 20);
m_pListCtrl->InsertColumn(5, _T("化学\n分数"), LVCFMT_LEFT, 20);
CHeaderCtrlEx* headerList = &m_pListCtrl->m_headerList;
HDITEM hdItem;
hdItem.mask = HDI_FORMAT;
int count = headerList->GetItemCount();
for (int i = 0; i < headerList->GetItemCount(); i++)
{
headerList->GetItem(i, &hdItem);
hdItem.fmt |= HDF_OWNERDRAW;
headerList->SetItem(i, &hdItem);
}
return TRUE;
效果如下: