MFC vc++ 中CTreeContrl如何自定义实现鼠标单击或双击响应事件 ,即重写类似于控件的响应事件或消息

代码部分摘录自“天上的猩猩的专栏”:https://blog.csdn.net/qq_23992597/article/details/51006920#commentsedit

目的:自定义修改mfc窗口的FileView中已有的树结构,而不是添加的树控件

实现的效果如图:点击“地图”后弹出框提示,点击响应效果与控件的响应事件类似

MFC vc++ 中CTreeContrl如何自定义实现鼠标单击或双击响应事件 ,即重写类似于控件的响应事件或消息_第1张图片

首先需要重写CtreeContrl:

① 在CViewTree类的.h头文件中添加代码:

afx_msg void OnDblClkTree(NMHDR* pNMHDR, LRESULT* pResult);//双击事件
afx_msg void OnClkTree(NMHDR* pNMHDR, LRESULT* pResult);//单击事件

② 添加后的.h文件如下:

#pragma once
 
/
// CViewTree 窗口
 
class CViewTree : public CTreeCtrl
{
// 构造
public:
	CViewTree();
 
// 重写
protected:
	virtual BOOL OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult);
 
// 实现
public:
	virtual ~CViewTree();
	afx_msg void OnDblClkTree(NMHDR* pNMHDR, LRESULT* pResult);
	afx_msg void OnClkTree(NMHDR* pNMHDR, LRESULT* pResult);
 
protected:
	DECLARE_MESSAGE_MAP()
};

③  CViewTree类的cpp源文件中实现该事件,代码如下:

#include "stdafx.h"
#include "ViewTree.h"
 
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
 
/
// CViewTree
 
CViewTree::CViewTree()
{
}
 
CViewTree::~CViewTree()
{
}
 
BEGIN_MESSAGE_MAP(CViewTree, CTreeCtrl)
	ON_NOTIFY_REFLECT(NM_DBLCLK, &CViewTree::OnDblClkTree)
	ON_NOTIFY_REFLECT(NM_CLICK, &CViewTree::OnClkTree)
END_MESSAGE_MAP()
 
/
// CViewTree 消息处理程序
 
BOOL CViewTree::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult)
{
	BOOL bRes = CTreeCtrl::OnNotify(wParam, lParam, pResult);
 
	NMHDR* pNMHDR = (NMHDR*)lParam;
	ASSERT(pNMHDR != NULL);
 
	if (pNMHDR && pNMHDR->code == TTN_SHOW && GetToolTips() != NULL)
	{
		GetToolTips()->SetWindowPos(&wndTop, -1, -1, -1, -1, SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOSIZE);
	}
 
	return bRes;
}
 
void CViewTree::OnDblClkTree(NMHDR* pNMHDR, LRESULT* pResult)
{
 
	HTREEITEM hTreeItem = GetSelectedItem(); 
	//以GetItemText()函数为例: 
	CString S1 = GetItemText(hTreeItem); 
	AfxMessageBox("You have selected "+S1);
 
	*pResult = 0;
 
}
 
void CViewTree::OnClkTree(NMHDR* pNMHDR, LRESULT* pResult)
{
 
	HTREEITEM hTreeItem = GetSelectedItem(); 
	//以GetItemText()函数为例: 
	CString S1 = GetItemText(hTreeItem); 
	AfxMessageBox("You have selected "+S1);
 
	*pResult = 0;
 
}

注意:添加的位置要正确。

以上即可实现CtreeContrl的点击事件

你可能感兴趣的:(MFC,VC++,C/C++)