2

Possible Duplicate:
C++ std::string conversion problem on Windows
How to convert std::string to LPCSTR?

I want to rename a window ( WM_SETTEXT ) to something else. In have a std::string that contains the new window name. I need to convert the std::string to "LPCTSTR", this is becouse SendMessage needs the name in "LPCTSTR".

I can't get this to work, Could some one help me to convert a string to a LPCTSTR?

Community
  • 1
  • 1
Laurence
  • 1,815
  • 4
  • 22
  • 35
  • possible duplicate of [C++ std::string conversion problem on Windows](http://stackoverflow.com/questions/874433/c-stdstring-conversion-problem-on-windows), or http://stackoverflow.com/questions/1200188/how-to-convert-stdstring-to-lpcstr, or possibly quite a few of the other "Related" questions on this page. – Mat Mar 25 '12 at 18:16
  • 1
    Is your program compiled in Unicode or ANSI mode? That affects what `LPCTSTR` really is. – Greg Hewgill Mar 25 '12 at 18:18
  • Using SetWindowTextA() is the quick fix. – Hans Passant Mar 25 '12 at 19:38
  • 3
    Oh @Hans, don't encourage the evil of ANSI text! ;-) – David Heffernan Mar 25 '12 at 20:03

1 Answers1

7

Use the c_str() method of std::string. This returns a C string, i.e. a pointer to a null-terminated character array.

SendMessage(Handle, WM_SETTEXT, 0, (LPARAM)str.c_str());

This is fine if you are compiling for ANSI. If you are compiling for Unicode then you should use wstring instead of string. If that's the case, just change to wstring and the call to SendMessage works exactly as written above.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • If I do that, then my window gets a strange name "?????_|" – Laurence Mar 25 '12 at 18:20
  • 6
    That's because you have a mismatch between ANSI and Unicode. If you target Unicode, use `wstring`. If you use ANSI, use `string`. I strongly urge you not to use ANSI in 2012. Build your app for Unicode and use `wstring`. Don't bother with `TCHAR` at all, it just confuses for no discernible gain, in my view. – David Heffernan Mar 25 '12 at 18:22