这一节的练习就是快速建立一个TreeVew,我们分成2步来完成,第1步是用WIN32 SDK,第2步是自己封装类来简化操作。
首先是WIN32 SDK建立一个TreeView:
1. 包含头文件:#include
2. 声明HWND hTreeView后,使用CreateWindow建立一个TreeView,为了方便观察,加上WS_BORDER出现边框
3. 使用和操作TreeView的结构体:TVINSERTSTRUCT tvs; 利用tvs.item.pszText来改变标题,tvs.hParent来指定是根目录还是某个目录的子节点
HWND hTreeView;
hTreeView = CreateWindow("SysTreeView32",NULL,WS_CHILD|WS_BORDER|
WS_VISIBLE|TVS_HASLINES|TVS_HASBUTTONS|TVS_LINESATROOT,
10,20,200,400,hWnd,NULL,hInst,NULL);
TVINSERTSTRUCT tvs;
tvs.item.mask = TVIF_TEXT;
tvs.hInsertAfter = TVI_LAST;
tvs.item.pszText = "Node1";
tvs.hParent = NULL; //根节点1
HTREEITEM hNode1 = (HTREEITEM)SendMessage(hTreeView,
TVM_INSERTITEM,0,(LPARAM)&tvs);
tvs.item.pszText = "Item1";
tvs.hParent = hNode1; //子节点1
(HTREEITEM)SendMessage(hTreeView,TVM_INSERTITEM,0,(LPARAM)&tvs);
tvs.item.pszText = "Item2";
tvs.hParent = hNode1; //子节点2
(HTREEITEM)SendMessage(hTreeView,TVM_INSERTITEM,0,(LPARAM)&tvs);
tvs.item.pszText = "Node2";
tvs.hParent = NULL; //根节点2
HTREEITEM hNode2 = (HTREEITEM)SendMessage(hTreeView,
TVM_INSERTITEM,0,(LPARAM)&tvs);
tvs.item.pszText = "Item3";
tvs.hParent = hNode2;
(HTREEITEM)SendMessage(hTreeView,TVM_INSERTITEM,0,(LPARAM)&tvs);
tvs.item.pszText = "Item4";
tvs.hParent = hNode2;
(HTREEITEM)SendMessage(hTreeView,TVM_INSERTITEM,0,(LPARAM)&tvs);
以上,就建立了一个treeView,同时我们也发现了,如果要添加很多个节点,我们的代码会不断的重复,为了代码复用以及方便,我们自己来封装一个类来简化代码。
封装一个类:
class MyTV
{
public:
MyTV(HWND hParent)
{
hWndTree = hParent;
m_tvs.item.mask = TVIF_TEXT;
m_tvs.hInsertAfter = TVI_LAST;
}
HTREEITEM Createmy(HTREEITEM hNode, CHAR * str); //添加节点
private:
TVINSERTSTRUCT m_tvs;
HWND hWndTree;
};
HTREEITEM MyTV::Createmy(HTREEITEM hNode, CHAR * str)
{
m_tvs.hParent = hNode;
m_tvs.item.pszText = str;
HTREEITEM hNode1 = (HTREEITEM)SendMessage
(hWndTree, TVM_INSERTITEM, 0, (LPARAM)&m_tvs);
return hNode1;
}
在此基础上,我们对TreeView的添加就非常方便了,结构体被隐藏了,结构体中的每项赋值也给隐藏了:
MyTV me(hTreeView);
HTREEITEM hNode1 = me.Createmy(NULL, "这是根节点1");
me.Createmy(hNode1, "子节点1");
me.Createmy(hNode1, "子节点2");
me.Createmy(hNode1, "子节点3");
me.Createmy(hNode1, "子节点4");
HTREEITEM hNode2 = me.Createmy(NULL, "这是根节点2");
me.Createmy(hNode2, "子节点1");
me.Createmy(hNode2, "子节点2");
me.Createmy(hNode2, "子节点3");
me.Createmy(hNode2, "子节点4");
程序显示如下:
这样,就可以通过读取文件的层级关系,用树控件显示出来,而且很方便,很迅速。