编写有提示的listbox控件
思路比较简单:我们首先构造一个自己mylistbox来继承listbox控件,然后在自己的mylistbox里添加一个ctooltipctrl控件(显示信息的载体).这样我们必须提供一个接口来创建ctooltipctrl控件.其次呢,控件创建后,它需要一个设置信息的接口.然后呢,当我们的鼠标移动时,它随着鼠标所在位置的改变,而显示不同的内容,因此它需要一个鼠标移动事件,在鼠标移动的时候进行进行信息设置.代码如下:列出了cpp文件的代码
BOOL CTipListBox::CreateToolTip()
{
if (NULL == m_toolTipMessage)
{
m_toolTipMessage = new CToolTipCtrl();
if (m_toolTipMessage->Create(this, TTS_ALWAYSTIP|TTS_NOPREFIX))
{
m_toolTipMessage->Activate(TRUE);
m_toolTipMessage->SetDelayTime(100);
m_toolTipMessage->SetMaxTipWidth(500);
m_toolTipMessage->AddTool(this);// 帮定控件tooltip
return TRUE;
}
}
return FALSE;
}
void CTipListBox::SetTipMessage(CString &message)
{
if (message.IsEmpty())
{
return ;
}
if (m_toolTipMessage->GetSafeHwnd() != NULL)
{
m_toolTipMessage->UpdateTipText(message, this); // 更新要显示的字符
}
else
{
if (CreateToolTip())
{
m_toolTipMessage->AddTool(this, message);
}
}
m_toolTipMessage->Activate(TRUE);
}
void CTipListBox::OnMouseMove(UINT nFlags, CPoint point)
{
CPoint pt;// 当前鼠标所在位置
GetCursorPos(&pt);
ScreenToClient(&pt);// 转化为客户区的坐标
CRect rect;// 控件的大小
GetClientRect(&rect);
BOOL inout;
CString message;
if (rect.PtInRect(pt))
{
int select = ItemFromPoint(pt, inout);// 鼠标所在的哪一条信息
GetText(select, message);
SetTipMessage(message);
}
}
BOOL CTipListBox::PreTranslateMessage(MSG* pMsg)
{
if (m_toolTipMessage->GetSafeHwnd() != NULL)
{
if (pMsg->message == WM_MOUSEMOVE)
{
m_toolTipMessage->RelayEvent(pMsg);
SendMessage(WM_MOUSEMOVE);
}
}
return CWnd::PreTranslateMessage(pMsg);
}