在C#中,如何在Windows 10中的“区域和语言”下选择“国家或地区”?

Cla*_*pel 3 c# country culture locale region

我运行的是 Windows 10。当我从开始菜单中打开“区域和语言设置”时,我可以选择“国家或地区”。我正在尝试在 C# 程序中获取该值。

我在丹麦。我尝试将我的国家/地区更改为德国(参见屏幕截图),但我无法获取返回德国的代码。重新启动计算机没有帮助。

我受此线程启发编写了一些代码。

我的代码如下所示(同时尝试各种事情,获取我能想到的所有地区/文化事物):

private static void Main(string[] args)
{
    Thread.CurrentThread.CurrentCulture.ClearCachedData();
    Thread.CurrentThread.CurrentUICulture.ClearCachedData();
    var thread = new Thread(() => ((Action) (() =>
    {
        Console.WriteLine("Current culture: {0}", Thread.CurrentThread.CurrentCulture.Name);
        Console.WriteLine("Current UI culture: {0}", Thread.CurrentThread.CurrentUICulture.Name);
        Console.WriteLine("Installed UI culture: {0}", CultureInfo.InstalledUICulture.Name);
        Console.WriteLine("Current region: {0}", RegionInfo.CurrentRegion.ThreeLetterISORegionName);
        Console.WriteLine("System default LCID: {0}", GetSystemDefaultLCID());
    }))());
    thread.Start();
    thread.Join();
    Console.ReadKey();
}

[DllImport("kernel32.dll")]
private static extern uint GetSystemDefaultLCID();
Run Code Online (Sandbox Code Playgroud)

它输出:

Current culture: en-DK
Current UI culture: en-US
Installed UI culture: en-US
Current region: DNK
System default LCID: 1033
Run Code Online (Sandbox Code Playgroud)

我怎样才能让我的程序检测到我选择了德国?我需要调用什么方法或属性?可能需要什么重新启动或清除缓存?

Cla*_*pel 5

我在这个帖子中找到了我的问题的答案。

我正在使用下面的代码,正如@SanjaySingh 在该线程中所提议的那样,并且仅进行了轻微修改。

如果我调用GetMachineCurrentLocation参数geoFriendlyname设置为5,我会得到我想要的三个字母的 ISO 区域代码(对于德国,这是"DEU")。

的值可以在此处geoFriendlyname找到。

public static class RegionAndLanguageHelper
{
    #region Constants

    private const int GEO_FRIENDLYNAME = 8;

    #endregion

    #region Private Enums

    private enum GeoClass : int
    {
        Nation = 16,
        Region = 14,
    };

    #endregion

    #region Win32 Declarations

    [DllImport("kernel32.dll", ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
    private static extern int GetUserGeoID(GeoClass geoClass);

    [DllImport("kernel32.dll")]
    private static extern int GetUserDefaultLCID();

    [DllImport("kernel32.dll")]
    private static extern int GetGeoInfo(int geoid, int geoType, StringBuilder lpGeoData, int cchData, int langid);

    #endregion

    #region Public Methods

    /// <summary>
    /// Returns machine current location as specified in Region and Language settings.
    /// </summary>
    /// <param name="geoFriendlyname"></param>
    public static string GetMachineCurrentLocation(int geoFriendlyname)
    {
        int geoId = GetUserGeoID(GeoClass.Nation); ;
        int lcid = GetUserDefaultLCID();
        StringBuilder locationBuffer = new StringBuilder(100);
        GetGeoInfo(geoId, geoFriendlyname, locationBuffer, locationBuffer.Capacity, lcid);

        return locationBuffer.ToString().Trim();
    }

    #endregion
}
Run Code Online (Sandbox Code Playgroud)