以下是一个遍历 ListView 控件项的 Win32 API 的解决方法,并包含一个简单的代码示例:
使用 ListView 控件的相关 Win32 API 函数:
示例代码:
#include
#include
#define ID_LISTVIEW 1001
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
static HWND hwndListView;
switch (msg) {
case WM_CREATE:
{
// 创建 ListView 控件
hwndListView = CreateWindow(WC_LISTVIEW, NULL, WS_VISIBLE | WS_CHILD | LVS_REPORT,
10, 10, 300, 200, hwnd, (HMENU)ID_LISTVIEW, NULL, NULL);
// 添加列
LVCOLUMN lvColumn;
lvColumn.mask = LVCF_TEXT | LVCF_WIDTH;
lvColumn.pszText = "Column 1";
lvColumn.cx = 100;
ListView_InsertColumn(hwndListView, 0, &lvColumn);
// 添加项
LVITEM lvItem;
lvItem.mask = LVIF_TEXT;
lvItem.pszText = "Item 1";
lvItem.iItem = 0;
lvItem.iSubItem = 0;
ListView_InsertItem(hwndListView, &lvItem);
lvItem.pszText = "Item 2";
lvItem.iItem = 1;
ListView_InsertItem(hwndListView, &lvItem);
lvItem.pszText = "Item 3";
lvItem.iItem = 2;
ListView_InsertItem(hwndListView, &lvItem);
break;
}
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
switch (wmId) {
case ID_LISTVIEW:
{
if (HIWORD(wParam) == LBN_SELCHANGE) {
// 遍历 ListView 控件的项
int itemCount = ListView_GetItemCount(hwndListView);
for (int i = 0; i < itemCount; i++) {
LVITEM lvItem;
lvItem.mask = LVIF_TEXT | LVIF_STATE;
lvItem.iItem = i;
lvItem.iSubItem = 0;
lvItem.pszText = new char[MAX_PATH];
lvItem.cchTextMax = MAX_PATH;
lvItem.stateMask = LVIS_SELECTED;
ListView_GetItem(hwndListView, &lvItem);
if (lvItem.state & LVIS_SELECTED) {
char text[MAX_PATH];
ListView_GetItemText(hwndListView, i, 0, text, MAX_PATH);
// 输出选中项的文本
OutputDebugString(text);
}
delete[] lvItem.pszText;
}
}
break;
}
}
break;
}
case WM_DESTROY:
{
PostQuitMessage(0);
break;
}
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = "MyClass";
wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
RegisterClassEx(&wcex);
HWND hwnd = CreateWindow("MyClass", "ListView Example", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 400, 300, NULL, NULL, hInstance, NULL);
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg