Skip to content

Visual Cpp

Luke31 edited this page Nov 15, 2016 · 3 revisions

Example Project: Cpp

Basic for localization in Visual C++ are resources in .dll or .exe Implementing Globalization / Multilingual feature in win32 API application

Hint: an alternative is using the GNU gettext library, see the other sample: [Visual Cpp Gettext](Visual Cpp Gettext)

Each resource contains a language identifier. The same resource with the same name may exist with different languages. To access these resources the Windows SDK LoadString, LoadBitmap etc. may be used.

Strings in your code should be in a String Table resource and retrieved using LoadString (or more neutrally FindResource).

  1. Create resource and add String Tables for both languages English and Japanese

    String Table English

    String Table Japanese

  2. Create the following wrapper function using LoadString for loading a string from a resource (Source: Stackoverflow post: c++, Win32 LoadString wrapper):

     std::wstring LoadStringW(unsigned int id)
     {
     	const wchar_t* p = nullptr;
     	int len = ::LoadStringW(nullptr, id, reinterpret_cast<LPWSTR>(&p), 0);
     	if (len > 0)
     	{
     		return std::wstring(p, static_cast<size_t>(len));
     	}
     	// Return empty string; optionally replace with throwing an exception.
     	return std::wstring();
     }
    
  3. Enable your application to support Unicode output in console as well as in stdout, use the wmain signature and set the following lines at the beginning of your application:

     int wmain(int argc, wchar_t* argv[])
     {
     	_setmode(_fileno(stdout), _O_U16TEXT); //_O_WTEXT
     	//stdout may now be written to file (First character must be ASCII if output is written to file)
     	std::wcout << L"Enabling Unicode support" << std::endl;
     	...
     }
    
  4. Load and output your string:

     //Load multi-lang resource
     std::wstring str = LoadStringW(IDS_HW);
    
     //Output using wprintf
     wprintf(str.c_str());
     std::wcout << std::endl;
    
     //Output using wcout
     std::wcout << str << std::endl;
    
  • Hint: Following includes are required:

      #include "stdafx.h"
      #include "resource.h" //Enables us to load our resources -> multi-lang strings
      #include <string>
      #include <iostream>
      #include <io.h> //for setting outputmode UNICODE
      #include <fcntl.h> //contains _O_U16TEXT