【问题标题】:CString to LPWSTR in mfc在 mfc 中将 CString 转换为 LPWSTR
【发布时间】:2013-10-09 18:40:40
【问题描述】:

我正在以 UNICODE 模式构建我的应用程序,并希望将 CString 转换为 LPWSTR。基本上我有一个包含 CString 作为成员变量的类,例如,

class MyClass
{
   CString TreeNodeName;
}

我想使用以下结构将项目插入树控件,

TVINSERTSTRUCT tvInsert;
tvInsert.hParent = ParentNode;
tvInsert.hInsertAfter = NULL;
tvInsert.item.mask = TVIF_TEXT;
tvInsert.item.lParam = (long)ClassObject;
tvInsert.item.pszText = ClassObject->TreeNodeName;  //Need this conversion

请帮助我如何将 CString TreeNodeName; 转换为 tvInsert.item.pszText

【问题讨论】:

  • 我知道您可能不知道这个问题的答案,但是您对 CString 中的文本使用什么编码?你会看到这个问题是无法回答的,除非你知道那条信息。如果你不知道,也许你可以解释一下你从哪里得到TreeNodeName 的值。
  • @john 感谢您的快速回复,基本上我将 XML 文件中的一些值存储到 TReeNodeName 中,这是正常的 ASCII 编码
  • 似乎我误会了,因为您处于 Unicode 模式,您可以按照乔纳森·波特的说法直接分配。我在想某种字符集翻译是必要的。

标签: c++ string visual-c++ unicode mfc


【解决方案1】:

除非我误解了这个问题,否则您只需将 CString 转换为 LPCTSTR 即可将其与 Windows API 函数一起使用。 See here for a description.

因为TVITEM::pszText 成员是LPTSTR,您需要再次转换为非常量,但是这对于TVM_INSERTITEM 这样的操作应该是安全的,因为您提供的字符串没有被修改。

tvInsert.item.pszText = (LPTSTR)(LPCTSTR)ClassObject->TreeNodeName;

【讨论】:

    猜你喜欢
    • 2013-09-21
    • 2010-11-02
    • 2014-08-23
    • 2011-08-12
    • 2011-09-07
    • 2011-04-12
    • 2011-05-17
    • 2011-12-10
    • 1970-01-01
    相关资源
    最近更新 更多