2012-03-25 61 views
1

可能重複:
C++ std::string conversion problem on Windows
How to convert std::string to LPCSTR?字符串到LPCTSTR

我想重新命名一個窗口(WM_SETTEXT)到別的東西。有一個包含新窗口名稱的std :: string。我需要將std :: string轉換爲「LPCTSTR」,這是因爲SendMessage需要「LPCTSTR」中的名稱。

我不能得到這個工作,有人可以幫我把字符串轉換爲LPCTSTR嗎?

+0

可能的[Windows上的C++ std :: string轉換問題](http://stackoverflow.com/questions/874433/c-stdstring-conversion-problem-on-windows)或http:// stackoverflow的重複。 com/questions/1200188/how-to-convert-stdstring-to-lpcstr,或者本頁面上其他相關的其他問題。 – Mat 2012-03-25 18:16:42

+1

您的程序是以Unicode還是ANSI模式編譯的?這會影響'LPCTSTR'的真實含義。 – 2012-03-25 18:18:00

+0

使用SetWindowTextA()是快速修復。 – 2012-03-25 19:38:04

回答

6

使用std::stringc_str()方法。這返回一個C字符串,即一個指向空終止字符數組的指針。

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

這很好,如果你正在爲ANSI編譯。如果您正在編譯Unicode,那麼您應該使用wstring而不是string。如果是這種情況,只需更改爲wstring,致電SendMessage的呼叫與上面所述完全相同。

+0

如果我這樣做,那麼我的窗口會得到一個奇怪的名字「????? _ |」 – Laurence 2012-03-25 18:20:03

+6

這是因爲您的ANSI和Unicode之間不匹配。如果您的目標是Unicode,請使用'wstring'。如果您使用ANSI,請使用'string'。我強烈建議你不要在2012年使用ANSI。爲Unicode構建應用程序並使用'wstring'。在我看來,根本不用「TCHAR」,它只是混淆了沒有明顯的收益。 – 2012-03-25 18:22:51