说明
以下只记录了使用的大概步骤,均是查阅MSDN得出或翻译出的结论,要想了解更多,还是自行去查阅MSDN吧。
步骤
- 构造CTreeCtrl对象
- 使用CTreeCtrl::Create创建对象
- 需要在节点处显示图片的话,就用CTreeCtrl::SetImageList设置下图片资源
- 使用CTreeCtrl::InsertItem插入节点数据
- 使用ON_NOTIFY_REFLECT或 ON_NOTIFY 宏去添加CTreeCtrl控件的事件响应(ON_NOTIFY宏是用在CTreeCtrl控件父窗口中,而ON_NOTIFY_REFLECT则是在CTreeCtrl本身的通知,所以要使用此宏,需要从CTreeCtrl继承一个类下来)
MSDN原文教程
Typical usage of a tree control (CTreeCtrl) follows the pattern below:
- The control is created. If the control is specified in a dialog box template or if you’re using CTreeView, creation is automatic when the
dialog box or view is created. If you want to create the tree control
as a child window of some other window, use theCreate member
function.- If you want your tree control to use images, set an image list by callingSetImageList. You can also change the indentation by
callingSetIndent. A good time to do this is inOnInitDialog (for
controls in dialog boxes) orOnInitialUpdate (for views).- Put data into the control by calling the CTreeCtrl’sInsertItem function once for each data item. InsertItem returns a handle to the
item you can use to refer to it later, such as when adding child
items. A good time to initialize the data is in OnInitDialog (for
controls in dialog boxes) or OnInitialUpdate (for views).- As the user interacts with the control, it will send various notification messages. You can specify a function to handle each of
the messages you want to handle by adding an ON_NOTIFY_REFLECT macro
in your control window’s message map or by adding an ON_NOTIFY macro
to your parent window’s message map. See Tree Control Notification
Messages later in this article for a list of possible notifications.- Call the various Set member functions to set values for the control. Changes that you can make include setting the indentation
and changing the text, image, or data associated with an item.- Use the various Get functions to examine the contents of the control. You can also traverse the contents of the tree control
with functions that allow you to retrieve handles to parents,
children, and siblings of a specified item. You can even sort the
children of a particular node.- When you’re done with the control, make sure it’s properly destroyed. If the tree control is in a dialog box or if it’s a
view, it and the CTreeCtrl object will be destroyed automatically.
If not, you need to ensure that both the control and the CTreeCtrl
object are properly destroyed.
代码示例
代码说明
- 以上初始化树型控件用到一份文件,文件是utf8格式的,以tab键来标识各级层次结构
- 代码中用到一张位图,位图是120*20大小的,包含6张20*20大小的图片
运行截图