VC 中使用 CToolTipCtrl 消失后不再出现的Bug。。。。

最近用WTL重写CGdipButton。从ButtonST中将CtoolTipCtrl的相关代码转过来,发现一个问题:

ToolTip可以显示,鼠标移开后再移动到button上也可以再次显示,但是按下button或者等待tootip自动消失后,tooptip就不会再显示了。。。

郁闷了几天今天偶然看到MSDN论坛的一个答复,(http://social.msdn.microsoft.com/Forums/en-US/dfea9abc-8535-4a43-918a-a78f88b77c70/tooltip-does-not-appear-after-click?forum=winforms)我又喷血了,因为在之前的代码中加两句代码就解决了。。。。

贴下相关代码

// GdipButton.h

#pragma once

class CGdipButton : public CWindowImpl<CGdipButton, CButton> {
public:
    CGdipButton();
    virtual ~CGdipButton();
    
    void SetTooltipText(LPCTSTR lpszText, BOOL bActivate = TRUE);

protected:
    BEGIN_MSG_MAP_EX(CGdipButton)
        MESSAGE_RANGE_HANDLER(WM_MOUSEFIRST, WM_MOUSELAST, OnMouseMessage)
        MSG_WM_MOUSEHOVER(OnMouseHover)
        MSG_WM_MOUSELEAVE(OnMouseLeave)
    END_MSG_MAP()

    LRESULT OnMouseMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
    void    OnMouseHover(WPARAM wParam, CPoint point);
    void    OnMouseLeave();

private:
    void InitToolTip();
    BOOL    m_bHovering;
    CToolTipCtrl    m_toolTip;
};
// GdipButton.cpp

#include "stdafx.h"
#include "GdipButton.h"

CGdipButton::CGdipButton() {
    m_bHovering = FALSE;
}

CGdipButton::~CGdipButton() {
}

LRESULT CGdipButton::OnMouseMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) {
    // track hover msg and leave msg
    if(WM_MOUSEMOVE == uMsg) {
        TRACKMOUSEEVENT tme;
        tme.cbSize = sizeof(TRACKMOUSEEVENT);
        tme.dwFlags = TME_HOVER | TME_LEAVE;
        tme.dwHoverTime = 20;
        tme.hwndTrack = m_hWnd;
        _TrackMouseEvent(&tme);
    }

    if(m_toolTip.IsWindow()) {
        m_toolTip.RelayEvent((LPMSG)m_pCurrentMsg);
    }

    bHandled = false;
    return 1;
}

void CGdipButton::OnMouseHover(WPARAM wParam, CPoint point) {
    if(!m_bHovering) {
        m_bHovering = TRUE;
        Invalidate();
    }
}

void CGdipButton::OnMouseLeave() {
  // 就是这两句
    // 要先判断下是否存在m_toolTip窗口,否则未添加toolTip的button会出错。。。
    if(m_toolTip.IsWindow()) {
        m_toolTip.Activate(FALSE);
        m_toolTip.Activate(TRUE);
    }

    m_bHovering = FALSE;
    Invalidate();
}

void CGdipButton::SetTooltipText(LPCTSTR lpszText, BOOL bActivate) {
    if(NULL == lpszText) {
        return;
    }
    InitToolTip();
    if (m_toolTip.GetToolCount() == 0) {
        CRect rectBtn; 
        GetClientRect(rectBtn);
        m_toolTip.AddTool(*this, lpszText, rectBtn, 1);
    }
    m_toolTip.UpdateTipText(lpszText, *this, 1);
    m_toolTip.Activate(bActivate);
}

void CGdipButton::InitToolTip() {
    if(NULL == m_toolTip.m_hWnd) {
        m_toolTip.Create(*this);
        m_toolTip.Activate(FALSE);
        m_toolTip.SetMaxTipWidth(400);
    }
}
原文地址:https://www.cnblogs.com/mforestlaw/p/3614040.html