在使用webview_window显示HTML时遇到显示中文乱码的问题,原因是vscode的编码方式为UTF-8,而vs的编码方式为gb2312,因此在vscode中传入显示参数,通过channel调用方法显示时因为编码方式的不同导致中文显示乱码,因此想要支持中文显示要对webview_window插件修改,增加编码格式转换的方法。
std::string utf8_to_gb2312(const char* utf8) {
int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len + 1];
memset(wstr, 0, len + 1);
MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
char* str = new char[len + 1];
memset(str, 0, len + 1);
WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);
std::string strTemp = str;
if (wstr) delete[] wstr;
if (str) delete[] str;
return strTemp;
}
同时webview2的NavigateToString方法接收wchar_t*的参数,而传入的参数为string,因此还需增加类型转换方法
wchar_t* c2w(const char* str) {
int length = strlen(str) + 1;
wchar_t* t = (wchar_t*)malloc(sizeof(wchar_t) * length);
memset(t, 0, length * sizeof(wchar_t));
MultiByteToWideChar(CP_ACP, 0, str, strlen(str), t, length);
return t;
}
至此再次调用该方法即可解决中文乱码问题
void Webview::LoadStringContent(const std::string& content) {
std::string temp = utf8_to_gb2312(content.c_str());
wchar_t* res = c2w(temp.c_str());
webview_->NavigateToString(res);
}
同时记录其他GB2312转UTF-8编码格式转换方法
std::string gb2312_to_utf8(const char* gb2312) {
int len = MultiByteToWideChar(CP_ACP, 0, gb2312, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len + 1];
memset(wstr, 0, len + 1);
MultiByteToWideChar(CP_ACP, 0, gb2312, -1, wstr, len);
len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
char* str = new char[len + 1];
memset(str, 0, len + 1);
WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
std::string strTemp = str;
if (wstr) delete[] wstr;
if (str) delete[] str;
return strTemp;
}
|