#include <Windows.h>
LRESULT CALLBACK NewWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_CREATE:
// 在新窗口中添加一些控件
CreateWindow(TEXT("STATIC"), TEXT("这是一个新窗口"), WS_VISIBLE | WS_CHILD, 10, 10, 150, 20, hwnd, NULL, NULL, NULL);
CreateWindow(TEXT("BUTTON"), TEXT("关闭"), WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON, 10, 40, 80, 30, hwnd, NULL, NULL, NULL);
break;
case WM_COMMAND:
if (LOWORD(wParam) == 1)
{
// 关闭按钮被点击时关闭新窗口
DestroyWindow(hwnd);
}
break;
case WM_CLOSE:
// 新窗口关闭时销毁窗口句柄
DestroyWindow(hwnd);
break;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// 注册新窗口类
WNDCLASS wc = {};
wc.lpfnWndProc = NewWindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = TEXT("NewWindowClass");
RegisterClass(&wc);
// 创建主窗口
HWND hwnd = CreateWindow(TEXT("BUTTON"), TEXT("主窗口"), WS_OVERLAPPEDWINDOW, 100, 100, 400, 300, NULL, NULL, hInstance, NULL);
// 创建菜单栏
HMENU hMenu = CreateMenu();
HMENU hSubMenu = CreatePopupMenu();
AppendMenu(hSubMenu, MF_STRING, 1, TEXT("新窗口"));
AppendMenu(hMenu, MF_POPUP, (UINT_PTR)hSubMenu, TEXT("文件"));
// 将菜单栏关联到主窗口
SetMenu(hwnd, hMenu);
// 显示主窗口
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
// 消息循环
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}