-2

SendDlgItemMessage() function for its last parameter take an explicit string such as L"TEST" and when I pass it a string or wstring variable it does not work at all;

if I write below code it does not add any string item to my LIST_BOX :

string str[10];
for(int i = 0; i<10; i++)
   str[i] = "Item " + i;
int index2 = SendDlgItemMessage(hdlg, IDC_LIST2, LB_ADDSTRING, 0, (LPARAM)str[MarkerNumber ]);

Can you help me to set this function for using string parameters?

user3811565
  • 29
  • 1
  • 5
  • 1
    You need to get the raw C-string from it: i.e. you need to call `str[i].c_str()` to get the `char*` or `wchar_t*` that the API is looking for – Thomas Russell Jul 09 '14 at 09:52
  • Check your code - you using variable i out of scope. – Sergei Nikulov Jul 09 '14 at 09:54
  • That code won't *compile*, much less execute with success. That isn't how you build a string with running integer suffix, and I can all-but-assure you `"Item " + i` isn't doing what you think it is. Regarding the actual call to set the item text, your array is of `string`, not `wstring`. `SendDlgItemMessageA(hdlg, IDC_LIST2, LB_ADDSTRING, 0, (LPARAM)str[i].c_str());`, but you need to generate the string correctly *first*. – WhozCraig Jul 09 '14 at 09:55
  • @Sergey I edited that;) here I write it wrong. in code it was true. – user3811565 Jul 12 '14 at 05:55

1 Answers1

1

The problem is that the API function SendDlgItemMessage doesn't know how to pass a std::string or std::wstring object. What you need to do is pass it the contained raw C-string within the string. You can do that by using the member function std::string::c_str() (which returns a const char* or std::wstring::c_str() which returns a const wchar_t*.

You can then use that as follows:

std::wstring szTest( L"Test String" );
int iIndex = SendDlgItemMessage( hDlg, IDC_LIST2, LB_ADDSTRING, 0, (LPARAM)szTest.c_str() );

However, as it stands at the moment your code will not even compile; there are scope errors and there is no conversion from std::string to LPARAM and so the cast is invalid. Moreover, when you are constructing your strings (which you presumably want to be "Item n" where n ranges over [1...10], you should do it as follows:

for( int i = 1; i <= 10; ++i )
{
     szStringArray[i] = L"Item " + std::to_wstring(i);
}
Thomas Russell
  • 5,870
  • 4
  • 33
  • 68