1.UTF8與UTF16編碼轉換
std::string ConvertFromUtf16ToUtf8(const std::wstring& wstr)
{
std::string convertedString;
int requiredSize = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, 0, 0, 0, 0);
if(requiredSize > 0)
{
std::vector<char> buffer(requiredSize);
WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &buffer[0], requiredSize, 0, 0);
convertedString.assign(buffer.begin(), buffer.end() - 1);
}
return convertedString;
}
std::wstring ConvertFromUtf8ToUtf16(const std::string& str)
{
std::wstring convertedString;
int requiredSize = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, 0, 0);
if(requiredSize > 0)
{
std::vector<wchar_t> buffer(requiredSize);
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, &buffer[0], requiredSize);
convertedString.assign(buffer.begin(), buffer.end() - 1);
}
return convertedString;
}
void SetWindowTextUtf8(HWND hWnd, const std::string& str)
{
std::wstring wstr = ConvertUtf8ToUtf16(str);
SetWindowTextW(hWnd, wstr.c_str());
}
std::string GetWindowTextUtf8(HWND hWnd)
{
std::string str;
int requiredSize = GetWindowTextLength(hWnd) + 1; //We have to take into account the final null character.
if(requiredSize > 0)
{
std::vector<wchar_t> buffer(requiredSize);
GetWindowTextW(hWnd, &buffer[0], requiredSize);
std::wstring wstr(buffer.begin(), buffer.end() - 1);
str = ConvertUtf16ToUtf8(wstr);
}
return str;
}
2.強制VisualStudio使用UTF-8編碼
- 方法1
在stdafx.h
頭文件中添加如下代碼:
#pragma execution_character_set("utf-8")
- 方法2
在c/c++屬性頁的命令行添加/execution-charset:utf-8
,如下圖
3.解決VisualStudio在調試窗口UTF8字符串顯示亂碼
參考http://www.nubaria.com/en/blog/?p=289
默認的, VC調試器只能正常顯示ANSI字符串及UNICODE字符串, 而UTF-8字符串及其他格式則無法顯示
這裏無需編寫插件及修改配置文件,只需要將要顯示的字符串拉到Watch中,並在變量後面添加,s8即可顯示
–>
同樣類型的功能也應該很熟悉
,數字 將變量拆分爲數組顯示, 數字是要顯示多少位, 此法對const char*這類原始字符串非常有用
,x
16進制查看
,hr
查看Windows HRESULT解釋
,wm
Windows消息,例如0x0010, wm 顯示 WM_CLOSE