MFC CTreeCtrl鼠标滑过节点显示图片
时间: 2023-12-14 08:09:25 浏览: 175
鼠标滑过显示图片
要实现鼠标滑过节点显示图片,可以使用CTreeCtrl的NM_CUSTOMDRAW消息来自定义绘制节点。具体实现步骤如下:
1. 响应CTreeCtrl的NM_CUSTOMDRAW消息,并在OnCustomDraw函数中处理。
2. 判断绘制的节点是否是鼠标滑过的节点,可以使用CTreeCtrl的HitTest函数。
3. 如果是鼠标滑过的节点,就在该节点的位置显示图片,可以使用CImageList的Draw函数。
下面是代码示例:
```
void CMyTreeCtrl::OnCustomDraw(NMHDR* pNMHDR, LRESULT* pResult)
{
NMTVCUSTOMDRAW* pNMCD = reinterpret_cast<NMTVCUSTOMDRAW*>(pNMHDR);
*pResult = CDRF_DODEFAULT;
switch (pNMCD->nmcd.dwDrawStage)
{
case CDDS_PREPAINT:
*pResult = CDRF_NOTIFYITEMDRAW;
break;
case CDDS_ITEMPREPAINT:
*pResult = CDRF_NOTIFYITEMDRAW;
break;
case CDDS_ITEMPREPAINT | CDDS_SUBITEM:
{
HTREEITEM hItem = reinterpret_cast<HTREEITEM>(pNMCD->nmcd.dwItemSpec);
if (hItem == GetHoverItem())
{
CRect rect;
GetItemRect(hItem, rect, TRUE);
rect.left += m_nIndent + 2;
rect.top += 1;
rect.bottom -= 1;
int nImage = GetItemImage(hItem, FALSE);
if (nImage != -1)
{
CImageList* pImageList = GetImageList(TVSIL_NORMAL);
if (pImageList != NULL)
{
pImageList->Draw(&pNMCD->nmcd.hdc, nImage, rect.TopLeft(), ILD_NORMAL);
}
}
}
}
break;
}
*pResult |= CDRF_NOTIFYPOSTPAINT;
}
HTREEITEM CMyTreeCtrl::GetHoverItem() const
{
HTREEITEM hItem = NULL;
CPoint pt;
GetCursorPos(&pt);
ScreenToClient(&pt);
UINT uFlags;
hItem = HitTest(pt, &uFlags);
if ((uFlags & TVHT_ONITEM) == 0)
{
hItem = NULL;
}
return hItem;
}
```
在OnMouseMove函数中,可以调用RedrawWindow函数来刷新树形控件,以便及时显示鼠标滑过的节点的图片。
```
void CMyTreeCtrl::OnMouseMove(UINT nFlags, CPoint point)
{
HTREEITEM hHoverItem = GetHoverItem();
if (hHoverItem != m_hHoverItem)
{
m_hHoverItem = hHoverItem;
RedrawWindow();
}
CTreeCtrl::OnMouseMove(nFlags, point);
}
```
阅读全文