环境: Win7 x64,VS2015
目标 : 打开指定文件夹,支持空格中文路径,字符集支持Unicode/多字节
代码:
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
std::wstring StringToWString(const std::string &str)
{
std::wstring wContext = L"";
int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0);
WCHAR* buffer = new WCHAR[len + 1];
MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len);
buffer[len] = '\0';
wContext.append(buffer);
delete[] buffer;
return wContext;
}
void OpenFolder(const string &path)
{
//字符集 支持Unicode 和 多字节
#ifdef _UNICODE
std::wstring tmp = StringToWString(path);
LPCWSTR dir = tmp.c_str();
ShellExecute(NULL, NULL, dir, NULL, NULL, SW_SHOWNORMAL);
#elif _MBCS
LPCSTR dir = path.c_str();
ShellExecute(NULL, NULL, dir, NULL, NULL, SW_SHOWNORMAL);
#endif
}
int main()
{
OpenFolder("C:\\Users\\Administrator\\Desktop\\中 国 ab");
return 0;
}