如何建立樹視圖控件

若要建立樹視圖控件,請使用 CreateWindowEx 函式,指定 視窗類別的WC_TREEVIEW 值。 載入通用控制項 DLL 時,樹檢視視窗類別會在應用程式的位址空間中註冊。 若要確保載入 DLL,請使用 InitCommonControls 函式。

您需要知道的事項

技術

必要條件

  • C/C++
  • Windows 使用者介面程序設計

指示

建立樹視圖控件的實例

下列範例會建立一個樹視圖控件,其大小會符合父視窗的工作區。 它也會使用應用程式定義的函式,將影像清單與控件產生關聯,並將專案新增至控件。

// 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訊息所指定的字型維度來判斷間距和版面配置。

使用樹視圖控件

CustDTv 範例說明樹視圖控件中的自定義繪製