用WIN API创建一个带edit文本框的窗口程序,并且edit文本框大小跟随窗口变化,窗口下部有"submit"和"quit"按钮,附件上"submit"和"quit"按钮的单击回调
时间: 2023-07-06 09:38:54 浏览: 64
好的,下面是创建一个带有edit文本框和按钮的窗口程序的代码:
```c++
#include <Windows.h>
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
const char CLASS_NAME[] = "My Window Class";
WNDCLASS wc = {};
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);
HWND hWnd = CreateWindowEx(
0,
CLASS_NAME,
"My Window",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 640, 480,
NULL, NULL, hInstance, NULL
);
if (hWnd == NULL) {
return 0;
}
ShowWindow(hWnd, nCmdShow);
MSG msg = {};
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
static HWND hEdit;
static HWND hButtonSubmit, hButtonQuit;
switch (message) {
case WM_CREATE: {
// 创建edit文本框
hEdit = CreateWindowEx(
WS_EX_CLIENTEDGE,
"EDIT",
"",
WS_CHILD | WS_VISIBLE | WS_VSCROLL | ES_LEFT | ES_MULTILINE | ES_AUTOVSCROLL,
0, 0, 0, 0,
hWnd,
NULL,
GetModuleHandle(NULL),
NULL
);
// 创建submit按钮
hButtonSubmit = CreateWindow(
"BUTTON",
"Submit",
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
0, 0, 0, 0,
hWnd,
NULL,
GetModuleHandle(NULL),
NULL
);
// 创建quit按钮
hButtonQuit = CreateWindow(
"BUTTON",
"Quit",
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
0, 0, 0, 0,
hWnd,
NULL,
GetModuleHandle(NULL),
NULL
);
break;
}
case WM_SIZE: {
// 窗口大小改变时,调整edit文本框和按钮的位置和大小
int cxClient = LOWORD(lParam);
int cyClient = HIWORD(lParam);
MoveWindow(hEdit, 0, 0, cxClient, cyClient - 80, TRUE);
MoveWindow(hButtonSubmit, cxClient / 2 - 80, cyClient - 70, 80, 30, TRUE);
MoveWindow(hButtonQuit, cxClient / 2 + 10, cyClient - 70, 80, 30, TRUE);
break;
}
case WM_COMMAND: {
// 处理按钮的单击事件
if (LOWORD(wParam) == (WORD)hButtonSubmit) {
MessageBox(NULL, "Submit clicked!", "Info", MB_OK);
} else if (LOWORD(wParam) == (WORD)hButtonQuit) {
PostQuitMessage(0);
}
break;
}
case WM_DESTROY: {
PostQuitMessage(0);
break;
}
default: {
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
return 0;
}
```
在上面的代码中,我们首先注册了一个窗口类,然后创建了一个窗口。在窗口创建时,我们创建了一个edit文本框和两个按钮。在窗口大小改变时,我们调整了edit文本框和按钮的位置和大小。在按钮的单击事件中,我们分别处理了"submit"和"quit"按钮的单击事件。
附上"submit"和"quit"按钮的单击回调,分别弹出一个消息框和退出程序:
```c++
case WM_COMMAND: {
// 处理按钮的单击事件
if (LOWORD(wParam) == (WORD)hButtonSubmit) {
MessageBox(NULL, "Submit clicked!", "Info", MB_OK);
} else if (LOWORD(wParam) == (WORD)hButtonQuit) {
PostQuitMessage(0);
}
break;
}
```
阅读全文