Listview Example

The following messages are sent to both the listbox and staticbox as a SendMessage API function parameter.

LB_ADDSTRING- add items to the listbox
LB_GETCURSEL – get index of currently selected item in listbox
LB_GETTEXT – retrieves listbox item text
WM_SETTEXT – sets value of static box display value

//Listbox Control Example<>
#include <windows.h>
#define IDC_LIST 1
#define ID_EDIT 2
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASSEX wc;
MSG msg;
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszMenuName = NULL;
wc.lpszClassName = TEXT("myWindowClass");
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
RegisterClassEx(&wc);
CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("myWindowClass"), TEXT("Listbox Demo"), WS_VISIBLE | WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 700, 200, NULL, NULL, hInstance, NULL);
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}


LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
static HWND hwndList, hwndStatic;
TCHAR buff[100];
TCHAR *names[] = {TEXT("Matthew"),TEXT("Mark"),TEXT("Luke"),TEXT("John")};
switch(msg) {
case WM_CREATE:
//create listbox
hwndList = CreateWindow(TEXT("ListBox"), TEXT(""), WS_CHILD | WS_VISIBLE | LBS_NOTIFY| WS_BORDER | WS_VSCROLL, 10, 10, 150, 80, hwnd, (HMENU) IDC_LIST, NULL, NULL);
//create staticbox
hwndStatic = CreateWindow(TEXT("static"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER,10, 90, 150, 25, hwnd, (HMENU) ID_EDIT, NULL, NULL);
//populates listbox
int i;
for (i = 0; i <4; i++) {
wsprintf(buff,names[i]);
SendMessage(hwndList, LB_ADDSTRING, 0, (LPARAM) buff);
}
break;
case WM_COMMAND:
//respond to listview click
if (LOWORD(wParam) == IDC_LIST) {
if (HIWORD(wParam) == LBN_SELCHANGE) {
TCHAR lbvalue[30];
//gets index of selected listview item
int sel = (int) SendMessage(hwndList, LB_GETCURSEL, 0, 0);
//get selected text
SendMessage(hwndList, LB_GETTEXT, sel,(LPARAM)lbvalue);
//sets staticbox to value of listbox text
SendMessage(hwndStatic, WM_SETTEXT, sel,(LPARAM)lbvalue);
}
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
}
return (DefWindowProc(hwnd, msg, wParam, lParam));
}