Search code examples
c++uwpc++-winrtcppwinrt

Getting system language UWP C++/WinRT


I wanted to get the system language (not the input language, but the overall system language) in the C++/WinRT app, but can't find a way for doing such. I googled and found that in Unity this can be done using System.Globalization.CultureInfo.CurrentCulture structure, which is not available in C++ code. Anybody's familiar with this?


Solution

  • Getting system language UWP C++/WinRT

    You can use the Language Class to get the system language. First, you need to include the header files it needs. For example:

    #include <winrt/Windows.System.UserProfile.h>
    #include <winrt/Windows.Globalization.h>
    
    void MainPage::ClickHandler(IInspectable const&, RoutedEventArgs const&)
    {
        auto topUserLaunghage = Windows::System::UserProfile::GlobalizationPreferences::Languages().GetAt(0);
        Windows::Globalization::Language language{topUserLaunghage};
        hstring displayName = language.DisplayName();
    }
    

    Update:

    When you change the Regional format, the date, time, etc will change its format, you could get the language that was most recently used to format dates and times by using ResolvedLanguage of DateTimeFormatter. For example:

    Windows::Globalization::GeographicRegion userRegion{};
    hstring regionCode = userRegion.CodeTwoLetter();
    Windows::Foundation::Collections::IVector<hstring> coll{ winrt::single_threaded_vector<hstring>() };
    coll.Append(regionCode);
    auto dateTimeFormatter = Windows::Globalization::DateTimeFormatting::DateTimeFormatter(L"longdate", coll);
    auto regionInfoName = dateTimeFormatter.ResolvedLanguage(); // This is the language from the Regional format