0

I want to read the text which the user has typed in a Edit control. after entering the text and pressing the button, I want to get the text and add it as an item into a comboBox. this is what I am doing in WM_COMMAND of the parent dialog:

case WM_COMMAND:

    if(HIWORD(wParam) == BN_CLICKED)
    {
        if ((HWND)lParam == Button[0])
        {



                int len = GetWindowTextLengthW(Button[2]) + 1;
                GetWindowTextW(Button[2], text, len);
                SendMessage(Button[1],(UINT) CB_ADDSTRING,(WPARAM) 0,(LPARAM) text);

                }
        }


    return 0;

but things goes wrong, sometime I get NULL in the "text" variable, sometimes just the first character of the string the user has entered and sometime weird ASCII like characters. what am I doing wron? any ideas ?

user667222
  • 179
  • 3
  • 16
  • How is `Button[2]` initialized? And you should probably be using `SendMessageW`. – chris Jun 01 '13 at 22:57
  • button[2] contains the handle of the edit box when it created by createWindow `Button[2] = CreateWindowW( L"edit", NULL, WS_CHILD | WS_VISIBLE|WS_OVERLAPPED|WS_BORDER, windowWidth - (windowWidth), windowHeigh,windowWidth ,windowHeight, handlW, (HMENU)ID_EDIT,instnc, NULL);` – user667222 Jun 01 '13 at 23:05
  • Apologies, I meant to say `text` >.> – chris Jun 01 '13 at 23:17
  • it is a global `LPWSTR` – user667222 Jun 01 '13 at 23:18
  • `SendMessageW` did no effect. the `text` was defined like `LPWSTR text;` and when I did this `LPWSTR text = L"myText"; it always ad `myText` into comboBox no matter what user entered in edit control – user667222 Jun 01 '13 at 23:22
  • You need to allocate space to hold the text. All you have is a pointer pointing to some unknown location and are trying to write into that. – chris Jun 01 '13 at 23:27
  • I allocated this way `memset(&text,0,len);` but still I get `NULL` – user667222 Jun 01 '13 at 23:38
  • Again, you're just writing 0s into an uninitialized pointer. – chris Jun 01 '13 at 23:46

1 Answers1

1

You need to allocate memory for the string. Here's how one would expect to do it in C++03:

std::vector<wchar_t> str(len);
GetWindowTextW(Button[2], &str[0], str.size());
SendMessageW(Button[1], CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(&str[0]));
chris
  • 60,560
  • 13
  • 143
  • 205
  • you nailed it. thank you so much. how can I be expert on this like you ? this problem takes me too long, although I work with c++ most of the time. – user667222 Jun 01 '13 at 23:58
  • 1
    @user667222, Go through a [book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) on C++ and browse through new SO questions a lot? Aside from doing things, that's pretty much my story. The winapi aspect is mostly experience, and a decent part Old New Thing. – chris Jun 02 '13 at 00:11