treeview,用C++实现:当前选中行字体变成蓝色,给出完整示例
时间: 2024-01-01 11:05:25 浏览: 25
以下是一个简单的treeview实现,支持当前选中行字体变成蓝色的效果:
```cpp
#include <windows.h>
#include <commctrl.h>
#pragma comment(lib, "comctl32.lib")
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
HWND hTreeView;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR szCmdLine, int iCmdShow)
{
static TCHAR szAppName[] = TEXT("TreeViewDemo");
HWND hwnd;
MSG msg;
WNDCLASS wndclass;
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = szAppName;
if (!RegisterClass(&wndclass))
{
MessageBox(NULL, TEXT("This program requires Windows NT!"),
szAppName, MB_ICONERROR);
return 0;
}
hwnd = CreateWindow(szAppName, TEXT("TreeView Demo"),
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hInstance, NULL);
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static HTREEITEM hSelectedItem = NULL;
switch (message)
{
case WM_CREATE:
{
hTreeView = CreateWindowEx(0, WC_TREEVIEW, NULL,
WS_CHILD | WS_VISIBLE | TVS_HASBUTTONS | TVS_LINESATROOT | TVS_HASLINES,
0, 0, 0, 0, hwnd, (HMENU)1, ((LPCREATESTRUCT)lParam)->hInstance, NULL);
TVINSERTSTRUCT tvInsert;
tvInsert.hParent = TVI_ROOT;
tvInsert.hInsertAfter = TVI_LAST;
tvInsert.item.mask = TVIF_TEXT;
tvInsert.item.pszText = TEXT("Item 1");
TreeView_InsertItem(hTreeView, &tvInsert);
tvInsert.item.pszText = TEXT("Item 2");
TreeView_InsertItem(hTreeView, &tvInsert);
tvInsert.item.pszText = TEXT("Item 3");
TreeView_InsertItem(hTreeView, &tvInsert);
}
return 0;
case WM_NOTIFY:
if (((LPNMHDR)lParam)->code == TVN_SELCHANGED)
{
if (hSelectedItem)
{
TVITEM tvItem;
tvItem.hItem = hSelectedItem;
tvItem.mask = TVIF_STATE;
tvItem.stateMask = TVIS_SELECTED;
tvItem.state = 0;
TreeView_SetItem(hTreeView, &tvItem);
}
hSelectedItem = ((LPNMTREEVIEW)lParam)->itemNew.hItem;
TVITEM tvItem;
tvItem.hItem = hSelectedItem;
tvItem.mask = TVIF_STATE;
tvItem.stateMask = TVIS_SELECTED;
tvItem.state = TVIS_SELECTED;
TreeView_SetItem(hTreeView, &tvItem);
return 0;
}
break;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
```
以上代码实现了一个简单的树形控件,当用户选中某一行时,选中行的字体颜色会变成蓝色。具体实现是,在`WM_NOTIFY`消息中捕获`TVN_SELCHANGED`消息,然后根据选中的行设置字体颜色。