Unicode for Windows applications can be summarized with a few simple rules:
- In your project settings in Visual Studio choose Unicode (FYI: on Windows, Unicode is always UTF16).
- Get a UTF8 to UTF16 and a UTF16 to UTF8 function. (You could write it yourself, or find it on the internet. I personally use the ones from the Poco C++ libraries).
- In your code always use std::string for your class and function interfaces.
- When you need to use a WinAPI call that takes a string parameter you can use the conversion functions to fill a local std::wstring, on which you can call the c_str() method to pass to the API function.
- If you need to obtain textual data from a WinAPI function, then usually need to create local TCHAR array on the stack, pass it to the function, construct a std::wstring from the result, and then convert it back to a std::string using your UTF16 to UTF8 conversion function.
Examples:
Getting text using stack-allocated array
std::string getCurrentDirectory()
{
TCHAR buffer[MAX_PATH];
::GetCurrentDirectory(sizeof(buffer)/sizeof(TCHAR), &buffer[0]);
return std::string(ToUTF8(buffer));
}
Getting text using dynamically-allocated buffer
std::string getWindowText(HWND inHandle)
{
std::string result;
int length = ::GetWindowTextLength(inHandle);
if (length > 0)
{
TCHAR * buffer = new TCHAR[length+1];
::GetWindowText(inHandle, buffer, length+1);
result = ToUTF8(buffer);
delete [] buffer;
}
return result;
}
Setting text
void setWindowText(HWND inHandle, const std::string & inText)
{
std::wstring utf16String = ToUTF16(inText);
if (0 == ::SetWindowText(inHandle, utf16String.c_str()))
{
ReportError("Setting the text on component failed. Last error: " + getLastError(::GetLastError()));
}
}
Hope this helps.