天天看點

編寫有提示的listbox控件

在MFC中幾乎所有的控件都有資訊提示,而惟有listbox卻沒有這樣的一個功能,每當我們把滑鼠移到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 (pMsg->message == WM_MOUSEMOVE)

            m_toolTipMessage->RelayEvent(pMsg);

            SendMessage(WM_MOUSEMOVE);

    return CWnd::PreTranslateMessage(pMsg);