如何创建 Tree-View 控件

若要创建树视图控件,请使用 CreateWindowEx 函数,指定窗口类 的WC_TREEVIEW 值。 加载公共控件 DLL 时,树视图窗口类在应用程序的地址空间中注册。 若要确保加载 DLL,请使用 InitCommonControls 函数。

需要了解的内容

技术

先决条件

  • C/C++
  • Windows 用户界面编程

说明书

创建 Tree-View 控件的实例

以下示例创建一个树视图控件,该控件的大小适合父窗口的工作区。 它还使用应用程序定义的函数将图像列表与控件相关联,并将项添加到控件。

// Create a tree-view control. 
// Returns the handle to the new control if successful,
// or NULL otherwise. 
// hwndParent - handle to the control's parent window. 
// lpszFileName - name of the file to parse for tree-view items.
// g_hInst - the global instance handle.
// ID_TREEVIEW - the resource ID of the control.

HWND CreateATreeView(HWND hwndParent)
{ 
    RECT rcClient;  // dimensions of client area 
    HWND hwndTV;    // handle to tree-view control 

    // Ensure that the common control DLL is loaded. 
    InitCommonControls(); 

    // Get the dimensions of the parent window's client area, and create 
    // the tree-view control. 
    GetClientRect(hwndParent, &rcClient); 
    hwndTV = CreateWindowEx(0,
                            WC_TREEVIEW,
                            TEXT("Tree View"),
                            WS_VISIBLE | WS_CHILD | WS_BORDER | TVS_HASLINES, 
                            0, 
                            0, 
                            rcClient.right, 
                            rcClient.bottom,
                            hwndParent, 
                            (HMENU)ID_TREEVIEW, 
                            g_hInst, 
                            NULL); 

    // Initialize the image list, and add items to the control. 
    // InitTreeViewImageLists and InitTreeViewItems are application- 
    // defined functions, shown later. 
    if (!InitTreeViewImageLists(hwndTV) || 
                !InitTreeViewItems(hwndTV))
    { 
        DestroyWindow(hwndTV); 
        return FALSE; 
    } 
    return hwndTV;
} 

注解

创建树视图控件时,还可以向其发送 WM_SETFONT 消息来设置要用于文本的字体。 在插入任何项目之前,应发送此消息。 默认情况下,树视图使用图标标题字体。 尽管可以使用 自定义绘图自定义每项的字体,但树视图控件使用 由WM_SETFONT 消息指定的字体尺寸来确定间距和布局。

  • 使用 Tree-View 控件