共用方式為


如何建立 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 控件

CustDTv 範例顯示如何在 Tree-View 控件中進行自定義繪製