#include <windows.h> // Windows 头文件
#include <commctrl.h> // Windows 控件头文件
// 表格的数据
const char* data[3][2] = {
//{ "Name", "Age" },
{ "Alice", "25" },
{ "Bob", "30" },
{ "Cai", "26" }
};
// 窗口过程函数
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_CREATE: // 窗口创建消息
{
// 创建表格控件
HWND hTable = CreateWindowEx(0, WC_LISTVIEW, "", // 创建列表视图控件
WS_VISIBLE | WS_CHILD | LVS_REPORT, // 窗口样式
10, 10, 200, 200, // 窗口位置和大小:横坐标、纵坐标、整个表格横向长度、整个表格纵向长度
hwnd, NULL, NULL, NULL); // 父窗口句柄、菜单句柄、实例句柄、创建参数
// 添加表格列
LVCOLUMN col;
col.mask = LVCF_TEXT | LVCF_WIDTH;
col.cx = 100; ///单元格横向长度
col.pszText = const_cast <char*>("Name"); // 列标题
ListView_InsertColumn(hTable, 0, &col); // 在列表视图控件中插入一列
col.pszText = const_cast <char*>("Age"); // 列标题
ListView_InsertColumn(hTable, 1, &col); // 在列表视图控件中插入一列
// 添加表格行
LVITEM item;
item.mask = LVIF_TEXT;
for (int i = 0; i < 3; i++)//行
{
item.iItem = i;
item.iSubItem = 0;
item.pszText = (LPSTR)data[i][0]; // 单元格内容
ListView_InsertItem(hTable, &item); // 在列表视图控件中插入一个项
item.iSubItem = 1;
item.pszText = (LPSTR)data[i][1]; // 单元格内容
ListView_SetItem(hTable, &item); // 设置列表视图控件中的项的属性
}
break;
}
case WM_DESTROY: // 窗口销毁消息
PostQuitMessage(0); // 退出消息循环
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam); // 默认消息处理函数
}
return 0;
}
// 程序入口函数
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
// 注册窗口类
WNDCLASS wc = { 0 };
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszClassName = "MyClass";
RegisterClass(&wc); // 注册一个窗口类
// 创建窗口
HWND hwnd = CreateWindowA("MyClass", "My Window", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 400, 200, NULL, NULL, hInstance, NULL); //数字——窗口的横向、纵向长度
// 显示窗口
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
// 消息循环
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}
C++ 窗口表格控件
于 2023-03-02 11:52:04 首次发布