How to create an array of controls in VC?
There are several ways to create control arrays in VC++.
- Using a regular C++ array, you can declare an array of pointers to controls, then use a loop to create each control individually and store it in the array.
#include <Windows.h>
#include <vector>
HWND hButtons[5]; // 控件指针数组
for (int i = 0; i < 5; i++) {
hButtons[i] = CreateWindowEx(0, L"BUTTON", L"Button", WS_VISIBLE | WS_CHILD,
10 + i * 100, 10, 80, 30, hWnd, NULL, hInstance, NULL);
}
- You can use std::vector to store control pointers, allowing for dynamic addition and removal of controls.
#include <Windows.h>
#include <vector>
std::vector<HWND> hButtons; // 控件指针向量
for (int i = 0; i < 5; i++) {
HWND hButton = CreateWindowEx(0, L"BUTTON", L"Button", WS_VISIBLE | WS_CHILD,
10 + i * 100, 10, 80, 30, hWnd, NULL, hInstance, NULL);
hButtons.push_back(hButton); // 添加控件指针到向量
}
- Utilize dynamic arrays: Control pointers can be dynamically saved using the new operator to allocate arrays.
#include <Windows.h>
HWND* hButtons = new HWND[5]; // 动态数组
for (int i = 0; i < 5; i++) {
hButtons[i] = CreateWindowEx(0, L"BUTTON", L"Button", WS_VISIBLE | WS_CHILD,
10 + i * 100, 10, 80, 30, hWnd, NULL, hInstance, NULL);
}
// 使用完后记得释放内存
delete[] hButtons;
The above are several common methods, the specific choice of which method depends on the specific needs and scenarios.