以下代码无法正常工作。我正在尝试从编辑控件获取文本,但它无法正常工作。通过尝试所有可能的代码来查找msdn等文档... ...
case WM_COMMAND:
switch(LOWORD(wParam)){
case 1:
::MessageBox(hwnd,"button clicked","message",MB_OK);
break;
case 2:
TCHAR t[20]; //
GetWindowText(text_box,t,19);// this is not working????????????????
::MessageBox(hwnd,t,t,MB_OK);
cout<<t;
break;
下面的参考文献是完整的代码:
#include <windows.h>
#include<iostream>
using namespace std;
const char g_szClassName[] = "myWindowClass";
// Step 4: the Window Procedure
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
HWND text_field, button , text_box;
char text_saved[20];
switch(msg)
{ case WM_CREATE:
text_field = CreateWindow("STATIC",
"Hello World",
WS_VISIBLE | WS_CHILD | WS_BORDER,
20,20, 90,25,
hwnd,
NULL,NULL,NULL);
button = CreateWindow("BUTTON",
"push button",
WS_VISIBLE | WS_CHILD | WS_BORDER,
20,50, 100,20,
hwnd,
(HMENU)1,NULL,NULL
) ;
text_box = CreateWindow("EDIT",
" ",
WS_VISIBLE | WS_CHILD | WS_BORDER,
20,80, 200,25,
hwnd,
NULL,NULL,NULL
);
CreateWindow("BUTTON",
"Save",
WS_VISIBLE | WS_CHILD | WS_BORDER,
20,120, 100,20,
hwnd,
(HMENU)2,NULL,NULL
);
break;
case WM_COMMAND:
switch(LOWORD(wParam)){
case 1:
::MessageBox(hwnd,"button clicked","message",MB_OK);
break;
case 2:
TCHAR t[20];
GetWindowText(text_box,t,19);
::MessageBox(hwnd,t,t,MB_OK);
cout<<t;
break;
}
break;
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASSEX wc;
HWND hwnd;
MSG Msg;
//Step 1: Registering the Window Class
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszMenuName = NULL;
wc.lpszClassName = g_szClassName;
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if(!RegisterClassEx(&wc))
{
MessageBox(NULL, "Window Registration Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);
return 0;
}
// Step 2: Creating the Window
hwnd = CreateWindowEx(
WS_EX_CLIENTEDGE,
g_szClassName,
"The title of my window",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 500,500,
NULL, NULL, hInstance, NULL);
if(hwnd == NULL)
{
MessageBox(NULL, "Window Creation Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);
return 0;
}
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
// Step 3: The Message Loop
while(GetMessage(&Msg, NULL, 0, 0) > 0)
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return Msg.wParam;
}
答案 0 :(得分:5)
您已将text_box
(以及其他变量)定义为WndProc
函数的本地,这意味着每次调用该函数处理消息时它们的值都会丢失。如果要将值从一条消息保留到下一条消息,则需要将它们移出函数范围(或使它们成为static
)。
答案 1 :(得分:-1)
这是一个重复工作的代码版本,用数字控件ID替换局部变量text_box
(它不会将信息从一个调用保留到下一个调用)并使用{{1} },从ANSI更改为Unicode文本,并修复其他一些东西,同时主要保持格式:
GetDlgItem