GetUserPreferredUILanguages() never returns more than two languages

前端 未结 1 765
不思量自难忘°
不思量自难忘° 2021-01-02 19:45

I\'m trying to retrieve the complete list of the user\'s preferred languages from a C++/Qt application, as configured in the \"Region & language\" page in the user\'s pr

相关标签:
1条回答
  • 2021-01-02 20:13

    GlobalizationPreferences.Languages is usable from unmanaged C++ because GlobalizationPreferences has DualApiPartitionAttribute. Here is a C++/WinRT example of using GlobalizationPreferences.Languages:

    #pragma once
    #include <winrt/Windows.Foundation.Collections.h>
    #include <winrt/Windows.System.UserProfile.h>
    #include <iostream>
    #pragma comment(lib, "windowsapp")
    
    using namespace winrt;
    using namespace Windows::Foundation;
    using namespace Windows::System::UserProfile;
    
    int main()
    {
        winrt::init_apartment();
    
        for (const auto& lang : GlobalizationPreferences::Languages()) {
            std::wcout << lang.c_str() << std::endl;
        }
    }
    

    And a WRL example for those who cannot migrate to C++ 17:

    #include <roapi.h>
    #include <wrl.h>
    #include <Windows.System.UserProfile.h>
    #include <iostream>
    #include <stdint.h>
    #pragma comment(lib, "runtimeobject.lib")
    
    using namespace Microsoft::WRL;
    using namespace Microsoft::WRL::Wrappers;
    using namespace ABI::Windows::Foundation::Collections;
    using namespace ABI::Windows::System::UserProfile;
    
    int main()
    {
        RoInitializeWrapper initialize(RO_INIT_MULTITHREADED);
        if (FAILED(initialize)) {
            std::cerr << "RoInitialize failed" << std::endl;
            return 1;
        }
    
        ComPtr<IGlobalizationPreferencesStatics> gps;
        HRESULT hr = RoGetActivationFactory(
            HStringReference(
                RuntimeClass_Windows_System_UserProfile_GlobalizationPreferences)
                .Get(),
            IID_PPV_ARGS(&gps));
        if (FAILED(hr)) {
            std::cerr << "RoGetActivationFactory failed" << std::endl;
            return 1;
        }
    
        ComPtr<IVectorView<HSTRING>> langs;
        hr = gps->get_Languages(&langs);
        if (FAILED(hr)) {
            std::cerr << "Could not get Languages" << std::endl;
            return 1;
        }
    
        uint32_t size;
        hr = langs->get_Size(&size);
        if (FAILED(hr)) {
            std::cerr << "Could not get Size" << std::endl;
            return 1;
        }
        for (uint32_t i = 0; i < size; ++i) {
            HString lang;
            hr = langs->GetAt(i, lang.GetAddressOf());
            if (FAILED(hr)) {
                std::cerr << "Could not get Languages[" << i << "]" << std::endl;
                continue;
            }
            std::wcout << lang.GetRawBuffer(nullptr) << std::endl;
        }
    }
    
    0 讨论(0)
提交回复
热议问题