//Listbox Control Example<>
#include <windows.h>
#define IDC_LIST 1
#define ID_EDIT 2
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
HINSTANCE g_hinst;
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow) {
MSG msg ;
WNDCLASS wc = {0};
wc.lpszClassName = TEXT("List Box");
wc.hInstance = hInstance;
wc.hbrBackground = GetSysColorBrush(COLOR_3DFACE);
wc.lpfnWndProc = WndProc;
wc.hCursor = LoadCursor(0, IDC_ARROW);
g_hinst = hInstance;
RegisterClass(&wc);
CreateWindow(wc.lpszClassName, TEXT("List Box"),WS_OVERLAPPEDWINDOW | WS_VISIBLE, 100, 100, 340, 200, 0, 0, hInstance, 0);
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int) 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, g_hinst, 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));
}
Last Updated: 17 September 2022