Reputation: 33
I'm getting really weird characters from the conversion. Any idea why? I get the "data" from an external device and i need to display it to win32 GUI. It had no problem when i
printf("%s\n",data);
in the console mode but having trouble when i migrate it to win32 which requires me to convert to TCHAR to display.
CHAR data[256];
TCHAR data1[256];
MultiByteToWideChar(CP_ACP,MB_COMPOSITE,data,-1,data1,0);
CreateWindow(TEXT("STATIC"), data1, WS_VISIBLE | WS_CHILD |
10, 50,300,300,hWnd, (HMENU) none, NULL, NULL);
By the way, using
hDLL=LoadLibrary("MyKad.dll");
in win32 couldn't work so I had to used
hDLL=LoadLibrary(TEXT("MyKad.dll"));
May I know is this right? Thanks
Upvotes: 1
Views: 493
Reputation: 613262
The reason that your code fails is that you pass 0
in the final parameter of MultiByteToWideChar
. You can fix your code by passing the length if data1
:
MultiByteToWideChar(CP_ACP, MB_COMPOSITE, data, -1, data1, 256);
Note also that you should be checking for errors when calling API functions. Had you done so you would have discovered that MultiByteToWideChar
was failing.
I use the following function to convert to UTF-16:
std::wstring MultiByteStringToWideString(const std::string& MultiByte,
const UINT CodePage)
{
std::wstring result;
int cchWideChar = MultiByteToWideChar(CodePage, 0, MultiByte.c_str(), -1,
NULL, 0);
if (cchWideChar > 0)
{
wchar_t* bufferW = new wchar_t[cchWideChar];
if (MultiByteToWideChar(CodePage, 0, MultiByte.c_str(), -1, bufferW,
cchWideChar) != 0)
{
result = std::wstring(bufferW);
}
delete[] bufferW;
}
return result;
}
So you could use this as follows:
std::wstring windowName = MultiByteStringToWideString(data, CP_ACP);
CreateWindow(L"STATIC", windowName.c_str(), ...);
Upvotes: 2