当我在 TextBox 中输入值然后单击按钮时, MessageBox 必须显示输入的值而不是空的MessageBox。 那么在我点击按钮后如何让输入的值显示在MessageBox上?
#include <windows.h>
LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) {
HWND TextBox;
char textSaved[20];
switch(Message) {
case WM_CREATE:
TextBox = CreateWindow("EDIT",
"",
WS_BORDER | WS_CHILD | WS_VISIBLE,
10,10,300,20,
hwnd, NULL, NULL, NULL);
CreateWindow("BUTTON",
"Go",
WS_VISIBLE | WS_CHILD | WS_BORDER,
420, 10, 70, 20,
hwnd, (HMENU) 1, NULL, NULL);
break;
case WM_COMMAND:
switch(LOWORD(wParam))
{
case 1:
int gwtstat =0;
gwtstat = GetWindowText(TextBox, &textSaved[0], 20);
::MessageBox(hwnd, textSaved, textSaved, MB_OK);
break;
}
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) {
WNDCLASSEX wc;
HWND hwnd;
MSG Msg;
memset(&wc,0,sizeof(wc));
wc.cbSize = sizeof(WNDCLASSEX);
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
//HBRUSH brush = CreateSolidBrush(RGB(0, 0, 255));
wc.hbrBackground = CreateSolidBrush(RGB(20, 60, 12));//(brush)(COLOR_WINDOW+1);
wc.lpszClassName = "WindowClass";
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if(!RegisterClassEx(&wc)) {
MessageBox(NULL, "Window Registration Failed!","Error!",MB_ICONEXCLAMATION|MB_OK);
return 0;
}
hwnd = CreateWindowEx(WS_EX_CLIENTEDGE,"WindowClass","Caption",WS_VISIBLE|WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
640,
480,
NULL,NULL,hInstance,NULL);
if(hwnd == NULL) {
MessageBox(NULL, "Window Creation Failed!","Error!",MB_ICONEXCLAMATION|MB_OK);
return 0;
}
while(GetMessage(&Msg, NULL, 0, 0) > 0) {
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return Msg.wParam;
}
答案 0 :(得分:3)
在HWND TextBox;
内声明WndProc
表示每次调用窗口过程时,其值都会重置(到未初始化的值)。如果要保存变量static
或全局变量所需的值。
答案 1 :(得分:2)
首先你需要获取文本框文本,在你的情况下它没有id,然后使用这个代码创建带有id的文本框,因为在你的情况下每次调用你的窗口过程时都会重置HWND TextBox:
CreateWindowW(L"EDIT", L"", WS_BORDER | WS_CHILD | WS_VISIBLE, 10,10,300,20, hwnd, (HMENU)2, NULL, NULL);
现在你的文本框有一个id,我们不需要HWND TextBox,使用GetDlgItem获取TextBox,使用GetWindowTextW获取TextBox的文本并存储在wchar_t数组中:
case 1:
int len = GetWindowTextLengthW(GetDlgItem(hwnd, 2)) + 1;
wchar_t text[len];
GetWindowTextW(GetDlgItem(hwnd, 2), text, len);
MessageBoxW(NULL, text, L"MsgFromTextBox", MB_OK);