Win32: How to create a ListBox control using the CreateWindowExW() function?

落花浮王杯 提交于 2019-12-04 08:59:01
Will Marcouiller

In order to dynamically create a control in Win32's you need the following code:

HWND hBtn
    , hLabel
    , hListbox
    , hTextBox;

void InitializeComponent(HWND hWnd) {
    HINSTANCE hInstance = GetModuleHandle(NULL);

    // Adding a Button.
    hBtn = CreateWindowExW(WS_EX_APPWINDOW
        , L"BUTTON", NULL
        , WS_CHILD | WS_VISIBLE
        , 327, 7, 70, 21
        , hWnd, NULL, hInstance, NULL);        

    SetWindowTextW(hBtn, L"&Button");

    // Adding a Label.
    hLabel = CreateWindowExW(WS_EX_CLIENTEDGE
        , L"STATIC", NULL
        , WS_CHILD | WS_VISIBLE
        , 7, 7, 50, 21
        , hWnd, NULL, hInstance, NULL);

    SetWindowTextW(hLabel, L"Label:");

    // Adding a ListBox.
    hListBox = CreateWindowExW(WS_EX_CLIENTEDGE
        , L"LISTBOX", NULL
        , WS_CHILD | WS_VISIBLE | ES_VSCROLL | ES_AUTOVSCROLL
        , 7, 35, 300, 200
        , hWnd, NULL, hInstance, NULL);

    // Adding a TextBox.
    hTextBox = CreateWindowExW(WS_EX_CLIENTEDGE
        , L"EDIT", NULL
        , WS_CHILD | WS_VISIBLE | ES_AUTOVSCROLL
        , 62, 7, 245, 21
        , hWnd, NULL, hInstance, NULL);

    SetWindowTextW(hTextBox, L"Input text here...");
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) {
    switch (Msg) {
        case WM_CREATE:
            InitializeComponent(hWnd);
            break;            
        default:
            return DefWindowProcW(hWnd, Msg, wParam, lParam);
    }
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) {
    // Declaring, defining, registering and creating window here...
    // Note that each Window/Control has to have its own Message handling function.
}
HWND hListBox; // Handle for list box control

hListBox = CreateWindowEx(
  WS_EX_CLIENTEDGE, // extended window styles
  "LISTBOX", // list box window class name
  NULL,
  WS_CHILD | WS_VISIBLE, // window styles
  7,   // horizontal position
  35,  // vertical position
  300, // width
  200, // height
  hWnd,
  NULL,
  hInstance,
  NULL
);

if (!hListBox){
  // failed to create list box window - take actions ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!