3

我正在尝试使用这行代码

startingfolder = _T("C:\\VSS\\" +  caseref);

但据我了解,我不允许在变量上使用 _T。基本上我试图将 SHBrowseForFolder 的起始文件夹设置为由之前分配的变量组成的路径。我花了很长时间试图绕过它,一直在搜索并找到有关 wstrings 的东西,但似乎没有任何效果。我希望我错过了一些容易的事情,因为我无法相信 _T 变量这么难。

void folderdialog2()
                 {    
                     PIDLIST_ABSOLUTE xx;
                     PCTSTR startingfolder; 

                     startingfolder = _T("C:\\VSS\\" +  caseref);
                     xx = ILCreateFromPath(startingfolder);

                     BROWSEINFO bi = { 0 };
                     bi.pidlRoot = xx;
                     bi.lpszTitle = _T("Pick a Directory");

                     LPITEMIDLIST pidl = SHBrowseForFolder ( &bi );
                     if ( pidl != 0 )
                     {
                         // get the name of the folder
                         TCHAR path[MAX_PATH];
                         if ( SHGetPathFromIDList ( pidl, path ) )
                         {
                             _tprintf ( _T("Selected Folder: %s\n"), path );                                                                           
                         }
                         // free memory used
                         IMalloc * imalloc = 0;
                         if ( SUCCEEDED( SHGetMalloc ( &imalloc )) )
                         {
                             imalloc->Free ( pidl );
                             imalloc->Release ( );
                         }                               
                     }           

                 }
4

2 回答 2

3

你可以这样做:

startingfolder = _T("C:\\VSS\\") +  caseref;

但如果caseref声明为std::string,则在您使用 Unicode 字符集时将无法编译。另一方面,如果将其声明为std::wstring,则在使用多字节字符集时将无法编译。

如果您需要您的程序同时支持这两种字符集,一种可能的方法是使用预处理器指令来定义一个类型别名,如果定义了符号则tstring解析为,如果没有定义则解析为,并将您的字符串变量声明为.std::wstring_UNICODEstd::stringtstring

#ifdef _UNICODE
typedef std::wstring tstring;
#else
typedef std::string tstring;
#endif

tstring casref = _T("something");
tstring startingfolder = _T("C:\\VSS\\") + caseref;

但是请注意,Windows 的非史前(即任何基于 NT 的)版本在内部使用 Unicode 字符,因此如果您没有特别的理由支持这两种配置,只需删除那些丑陋的宏(包括_T)并使用L前缀用于字符串文字(例如L"Hello")结合std::wstring(以及广泛版本的流,如果您正在使用它们)。

于 2013-03-16T23:41:46.683 回答
2

而不是这个:

PCTSTR startingfolder;
startingfolder = _T("C:\\VSS\\" +  caseref);

做这个:

wstring const startingfolder = wstring() + L"C:\\VSS\\" + caseref;

并将您的字符串类型更改为宽字符串等,并确保UNICODE在包含<windows.h>.

Windows API 基于 UTF-16 字符串表示,使用 16 位wchar_t. 当您使用 ANSI 函数时,它必须在宽字符基础 API 之间进行转换。所以使用 ANSI 字符串是

  • 效率低下。
  • 有限(不能处理一般的 Unicode 字符)。
  • 很多额外的工作,但很可能仍然存在错误。

如果您使用仍然可以针对 Windows 9x 的非常旧的工具,并且您的意思是针对 Windows 9x,并且您不能使用 Layer for Unicode,那么您需要支持 ANSI,因为您在 DLL 中使用 MFC 并且您不觉得你要重建它。但是,您是否真的针对 Windows 9x 和 DLL 中的 MFC 并使用了足够老的工具来做到这一点?我对此表示怀疑!

所以,在任何地方都使用宽字符串。


总结一下,忘记那些愚蠢的_T宏。

于 2013-03-17T01:20:05.673 回答