在Windows平台上,使用Win32 API可以创建具有最大化、最小化功能的窗口。下面是使用Win32 API实现的示例代码:
```c
#include <windows.h>
// 全局变量,用于存储窗口的初始宽度和高度
int g_nWidth = 640;
int g_nHeight = 480;
// 窗口过程函数
LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
case WM_CREATE:
SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)LoadIcon(NULL, IDI_APPLICATION));
SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM)LoadIcon(NULL, IDI_APPLICATION));
break;
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
hdc = GetDC(hwnd);
DrawMenuBar(hdc);
ReleaseDC(hwnd, hdc);
EndPaint(hwnd, &ps);
break;
case WM_SIZE:
MoveWindow(hwnd, 0, 0, g_nWidth, g_nHeight, TRUE);
break;
case WM_COMMAND:
int cmdID = LOWORD(wParam);
if (cmdID == IDM_EXIT)
{
PostQuitMessage(0);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASS wc = {};
wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.lpszClassName = TEXT("MyWindowClass");
wc.hInstance = hInstance;
wc.lpfnWndProc = WindowProcedure;
if (!RegisterClass(&wc))
return FALSE;
HMENU hMenu = LoadMenu(hInstance, MAKEINTRESOURCE(IDC_MENU));
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_ACCELERATOR));
HWND hwnd = CreateWindowEx(0, "MyWindowClass", "我的窗口",
WS_OVERLAPPEDWINDOW | WS_MINIMIZEBOX,
CW_USEDEFAULT, CW_USEDEFAULT, g_nWidth, g_nHeight,
NULL, hMenu, hInstance, NULL);
if (!hwnd)
return FALSE;
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
MSG msg = {};
while (GetMessage(&msg, NULL, 0, 0))
{
if (hAccelTable && TranslateAccelerator(hwnd, hAccelTable, &msg))
{
continue;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int) msg.wParam;
}
```
在这个例子中,我们定义了一个窗口类,并设置了窗口过程函数`WindowProcedure`。在`WM_CREATE`消息处理中,我们设置窗口图标。`WM_PAINT`消息处理中,我们进行了窗口的绘制。`WM_SIZE`消息处理中,我们通过`MoveWindow`函数更新了窗口的位置和大小。
注意,为了使窗口能够最大化或最小化,我们在创建窗口时使用了`WS_OVERLAPPEDWINDOW`样式,并且包含了`WS_MINIMIZEBOX`样式,这样窗口就会有一个最小化按钮。窗口的其他标准行为(如移动、改变大小等)都是由操作系统自动处理的。