WIN API创造静态文本框,且在主窗口正中间
时间: 2024-03-03 10:50:57 浏览: 120
【Win32示例】压力转换工具
好的,以下是WIN API创建静态文本框并置于主窗口中央的代码:
```c++
#include <Windows.h>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
static TCHAR szAppName[] = TEXT("HelloWin");
HWND hwnd;
MSG msg;
WNDCLASS wndclass;
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = szAppName;
if (!RegisterClass(&wndclass))
{
MessageBox(NULL, TEXT("This program requires Windows NT!"), szAppName, MB_ICONERROR);
return 0;
}
hwnd = CreateWindow(szAppName, TEXT("Hello, World!"), WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hInstance, NULL);
// 创建静态文本框
HWND hStatic = CreateWindow(TEXT("STATIC"), TEXT("Hello, World!"),
WS_CHILD | WS_VISIBLE | SS_CENTER, 0, 0, 0, 0,
hwnd, NULL, hInstance, NULL);
// 获取主窗口的客户区大小
RECT rect;
GetClientRect(hwnd, &rect);
// 获取静态文本框的大小
RECT staticRect;
GetClientRect(hStatic, &staticRect);
// 计算静态文本框的位置
int x = (rect.right - rect.left - staticRect.right + staticRect.left) / 2;
int y = (rect.bottom - rect.top - staticRect.bottom + staticRect.top) / 2;
// 移动静态文本框到主窗口中央
MoveWindow(hStatic, x, y, staticRect.right - staticRect.left, staticRect.bottom - staticRect.top, TRUE);
ShowWindow(hwnd, iCmdShow);
UpdateWindow(hwnd);
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return 0;
}
```
在这个示例代码中,我们使用了`CreateWindow`函数创建了一个静态文本框,并使用`GetClientRect`函数和`MoveWindow`函数计算并移动了它的位置,使其置于主窗口的正中央。
阅读全文