Combobox Example

The following messages are sent to both populate the combo box and detect changes –

CB_ADDSTRING – Adds a string to the list box of a combo box.
CBN_SELCHANGE – Sent when the user changes the current selection in the list box of a combo box.
CB_GETCURSEL – sends to the combobox to retrieve the index of the currently selected item.
CB_GETLBTEXT – retrieves a string from the list of a combo box.

//combobox control demo
#include <windows.h>
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("Combobox control 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 hwndCombo, hwndStatic;
const TCHAR *items[] = { TEXT("Paris"), TEXT("London"), TEXT("Berlin"), TEXT("Rome") };
switch(msg)
{
case WM_CREATE:
//create combo box
hwndCombo = CreateWindow(TEXT("combobox"), NULL, WS_CHILD | WS_VISIBLE | CBS_DROPDOWN,10, 10, 120, 110, hwnd, NULL, NULL, NULL);
//create static control
hwndStatic = CreateWindow(TEXT("static"), TEXT(""), WS_CHILD | WS_VISIBLE|WS_BORDER,150, 10, 90, 25, hwnd, NULL, NULL, NULL);
int i;
for (i = 0; i < 4; i++ )
{
//populate combo box
SendMessage(hwndCombo, CB_ADDSTRING, 0, (LPARAM) items[i]);
}
break;
case WM_COMMAND:
//respond to combo box selection
if ( HIWORD(wParam) == CBN_SELCHANGE) {
TCHAR strText[255] = TEXT("\0");
//get position of selected item
LRESULT sel = SendMessage(hwndCombo, CB_GETCURSEL, 0, 0);
//get selected item text
SendMessage(hwndCombo,CB_GETLBTEXT, sel,(LPARAM)strText);
//set value of static bex to value selected in combo box
SetWindowText(hwndStatic, strText);
SetFocus(hwnd);
} break;
case WM_DESTROY:
PostQuitMessage(0);
break;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}