Skip to content

Instantly share code, notes, and snippets.

@pedrolamas
Last active August 15, 2021 14:36
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedrolamas/ab61e75b9c9f31b7e14b485636f11dcc to your computer and use it in GitHub Desktop.
Save pedrolamas/ab61e75b9c9f31b7e14b485636f11dcc to your computer and use it in GitHub Desktop.
Helper class to return the correct CultureInfo in UWP apps
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
public class CultureInfoHelper
{
[DllImport("api-ms-win-core-localization-l1-2-0.dll", CharSet = CharSet.Unicode)]
private static extern int GetLocaleInfoEx(string lpLocaleName, uint LCType, StringBuilder lpLCData, int cchData);
private const uint LOCALE_SNAME = 0x0000005c;
private const string LOCALE_NAME_USER_DEFAULT = null;
private const string LOCALE_NAME_SYSTEM_DEFAULT = "!x-sys-default-locale";
private const int BUFFER_SIZE = 530;
public static CultureInfo GetCurrentCulture()
{
var name = InvokeGetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SNAME);
if (name == null)
{
name = InvokeGetLocaleInfoEx(LOCALE_NAME_SYSTEM_DEFAULT, LOCALE_SNAME);
if (name == null)
{
// If system default doesn't work, use invariant
return CultureInfo.InvariantCulture;
}
}
return new CultureInfo(name);
}
private static string InvokeGetLocaleInfoEx(string lpLocaleName, uint LCType)
{
var buffer = new StringBuilder(BUFFER_SIZE);
var resultCode = GetLocaleInfoEx(lpLocaleName, LCType, buffer, BUFFER_SIZE);
if (resultCode > 0)
{
return buffer.ToString();
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment