今天测试发现CSWComboBox虽然下拉列表里面可以显示图标了,但是处于非下拉状态下,却只能显示文字,感觉有点点遗憾,于是改进了一下。现在非下拉状态下也可以显示图标了,效果图如下:
具体实现思路就是把子窗体CEdit设置一个偏移,左边空出来的部分用于显示图标,修改核心代码如下:
// 获取子控件CEdit
CEdit* CSWComboBox::FindChildEdit()
{
::CWnd *pWnd = GetWindow(GW_CHILD);
while (pWnd)
{
TCHAR classname[256];
::GetClassName(pWnd->m_hWnd, classname, 256);
if (lstrcmpi(classname, _T("Edit")) == 0)
break;
if (pWnd)
pWnd = pWnd->GetNextWindow();
}
return (CEdit*)pWnd;
}
// 偏移CEdit子窗体位置
void CSWComboBox::SetChildEditOffset(int nOffset/* = 20*/)
{
CEdit *pEdit = FindChildEdit();
CRect rcEditWindow; pEdit->GetWindowRect(rcEditWindow);
CRect rcWindow; GetWindowRect(rcWindow);
rcEditWindow.left = nOffset + 3;
rcEditWindow.top = 6; // 相对位置本来是3,考虑到文本居中显示,6比较合适
rcEditWindow.right = rcWindow.Width() - 20;
rcEditWindow.bottom = rcWindow.Height() - 3;
pEdit->MoveWindow(rcEditWindow);
}
void CSWComboBox::PreSubclassWindow()
{
// TODO: 在此添加专用代码和/或调用基类
SetWindowLong(m_hWnd, GWL_EXSTYLE, GetWindowLong(m_hWnd, GWL_STYLE) | BS_OWNERDRAW);
CComboBox::PreSubclassWindow();
}