MFC鼠标悬停与离开

鼠标悬停与离开

说明: MFC默认的情况下,是不会触发鼠标悬停和离开的消息。

手动添加输小悬停和离开消息及消息处理函数

  1. 声明并定义函数(其中IDC_ BUTTON_ OK为目标按钮,IDC_ EDIT_ DEST为任意Edit控件,只为转移焦点)

    LRESULT xxxDlg::OnMouseLeave(WPARAM Wparam, LPARAM lParam)
    {
        // TODO:  在此添加消息处理程序代码和/或调用默认值
        POINT p;
        GetCursorPos(&p);
        CWnd *hwnd;
        hwnd = WindowFromPoint(p);
        CWnd *hWndOk = GetDlgItem(IDC_BUTTON_OK);
        if (hWndOk == hwnd)
        {
            GetDlgItem(IDC_BUTTON_OK)->SetFocus();
            m_bEditHover = FALSE;
        }
        m_bTracking = TRUE;
        return 0;
    }
    
    
    LRESULT xxxDlg::OnMouseHover(WPARAM Wparam, LPARAM lParam)
    {
        // TODO:  在此添加消息处理程序代码和/或调用默认值
        GetDlgItem(IDC_STATIC)->SetFocus();
        if (m_bEditHover)
        {
            GetDlgItem(IDC_EDIT_DEST)->SetFocus();
        }
        m_bTracking = FALSE;
        return 0;
    }
    
  2. 利用框架添加鼠标移动消息

    void CChoseWay::OnMouseMove(UINT nFlags, CPoint point)
    {
        // TODO:  在此添加消息处理程序代码和/或调用默认值
        if (m_bTracking)
        {
            TRACKMOUSEEVENT tme;
            tme.cbSize = sizeof(TRACKMOUSEEVENT);
            tme.dwFlags = TME_LEAVE | TME_HOVER;
            tme.hwndTrack = this->m_hWnd;
            tme.dwHoverTime = 100;
            if (::_TrackMouseEvent(&tme))
            {
                m_bTracking = FALSE;
            }
        }
        CDialogEx::OnMouseMove(nFlags, point);
    }
    

    tme.dwHoverTime = 100,意为停在按钮上100ms才会触发悬停消息。

  3. 手动添加消息响应

    BEGIN_MESSAGE_MAP(CChoseWay, CDialogEx)
        ON_BN_CLICKED(IDC_BUTTON_OK, &CChoseWay::OnBnClickedButton1)
        ...
        ON_MESSAGE(WM_MOUSEHOVER, OnMouseHover)
        ON_MESSAGE(WM_MOUSELEAVE, OnMouseLeave)
        ON_WM_MOUSEMOVE()
    END_MESSAGE_MAP()
    

你可能感兴趣的:(MFC学习)