控件–ComboBoxEx32-WindowsAPI论坛-WindowsAPI-津桥芝士平台

控件–ComboBoxEx32

使用WindowsAPI,创建ComboBoxEx32控件:

#include <windows.h>
#include <commctrl.h>
#pragma comment(lib, "comctl32.lib")
#define COMBOBOXEX_ID 101

HINSTANCE hInst;

LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) 
{
    switch (message) 
    {
    case WM_CREATE: 
    {
        INITCOMMONCONTROLSEX icex;
        icex.dwICC = ICC_USEREX_CLASSES; // Ensure the ComboBoxEx class is set up.
        InitCommonControlsEx(&icex);

        HWND hwndComboBoxEx = CreateWindowEx(0, WC_COMBOBOXEX, NULL,
            WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST,
            10, 10, 230, 300, // 宽度增加,以便更好地查看项
            hwnd, (HMENU)COMBOBOXEX_ID, hInst, NULL);

        // Adding items with strings
        COMBOBOXEXITEM cbei;
        ZeroMemory(&cbei, sizeof(cbei));
        cbei.mask = CBEIF_TEXT; // 设置项需要文本

        wchar_t items[5][20] = {L"Apple", L"Banana", L"Cherry", L"Date", L"Elderberry"};
        for (int i = 0; i < 5; ++i) 
        {
            cbei.pszText = items[i];
            cbei.cchTextMax = wcslen(items[i]);
            cbei.iItem = i;
            SendMessage(hwndComboBoxEx, CBEM_INSERTITEM, 0, (LPARAM)&cbei);
        }

        break;
    }
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hwnd, message, wParam, lParam);
    }
    return 0;
}

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR szCmdLine, int iCmdShow) 
{
    hInst = hInstance;
    WNDCLASS wc = {};
    wc.lpfnWndProc = WndProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = L"SampleWindowClass";
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    RegisterClass(&wc);

    HWND hwnd = CreateWindowEx(0, L"SampleWindowClass", L"ComboBoxEx32 Example",
        WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 270, 200,
        NULL, NULL, hInstance, NULL);

    ShowWindow(hwnd, iCmdShow);
    UpdateWindow(hwnd);

    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0)) 
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return (int)msg.wParam;
}

效果图:

image

 

请登录后发表评论

    没有回复内容