unable to get text from edit control in winapi [cl

2019-09-07 10:51发布

问题:

I'm not able to retrieve any text from the edit control I have on my main window. I can set the text, which does show up when the window is drawn, but I can not get the text, which I would like to display in a MessageBox. I tried both "SendMessage()" and "GetWindowText()" but both do the same thing. It appears the length of text I'm retrieving is also invalid, so the edit has no value even though I can see text in it.

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
HWND addCust, editCust1, editCust2;

switch (message) {
case WM_CREATE: {
    addCust = CreateWindow(L"BUTTON",L"addCust",
                   WS_CHILD|WS_VISIBLE|BS_DEFPUSHBUTTON,
                   140,70,100,25,hWnd,(HMENU)IDC_ADDCUST,NULL,NULL);
    editCust1 = CreateWindowEx(WS_EX_CLIENTEDGE,L"EDIT",L"",
                    WS_CHILD|WS_VISIBLE|ES_AUTOHSCROLL,
                    50,100,200,20,hWnd,(HMENU)IDC_EDITCUST1,NULL,NULL);
    editCust2 = CreateWindowEx(WS_EX_CLIENTEDGE,L"EDIT",L"",
                    WS_CHILD|WS_VISIBLE|ES_AUTOHSCROLL,
                    50,130,200,20,hWnd,(HMENU)IDC_EDITCUST2,NULL,NULL);
    SendMessage(editCust1,WM_SETTEXT,NULL,(LPARAM)L"first name");
    SendMessage(editCust2,WM_SETTEXT,NULL,(LPARAM)L"last name");
    break;
}
case WM_COMMAND:
    wmId    = LOWORD(wParam);
    wmEvent = HIWORD(wParam);
    case IDC_ADDCUST: {
        TCHAR buff[64] = { '\0' };
        int len = SendMessage(editCust1, WM_GETTEXTLENGTH, 0, 0);
        SendMessage(editCust1, WM_GETTEXT, len+1, (LPARAM)buff);
        GetWindowText(editCust1, buff, len+1);
        MessageBox(NULL, buff, L"Information", MB_ICONINFORMATION);
        break;
        }
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    break;
default:
    return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}

回答1:

 HWND addCust, editCust1, editCust2;

That cannot work, these are local variables. They lose their value after the WM_CREATE message handler runs and the WndProc() method exits. The variables contain garbage when you use editCust1 again in the WM_COMMAND handler. Easy to see with a debugger btw. You need to make them global variables so they maintain their values.

The buff declaration is wrong as well, it can only contain 63 characters. When the edit control actually contains 64 characters or more you'll corrupt the stack frame and (hopefully) crash your program. Use malloc() to create a buffer that's large enough.

These are C language programming traps, they have little to do with the Windows api. Hard to give advice beyond "go slower", you do need to know how C works before Windows stops giving you headaches like this.