编写有提示的listbox控件 2008-06-29 17:13

在MFC中几乎所有的控件都有信息提示,而惟有listbox却没有这样的一个功能,每当我们把鼠标移到listbox上控件时,啥玩意儿都没有是不是很气馁啊,所以我今天特地写了一个简单的有提示的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);
}

猜你喜欢

转载自www.cnblogs.com/lu-ping-yin/p/10988719.html