gpt4 book ai didi

c# - 在C#中,如何获取Windows 10中 "Country or region"下选中的 "Region & language"?

转载 作者:行者123 更新时间:2023-11-30 21:38:13 28 4
gpt4 key购买 nike

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

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

我写了一些受 this thread 启发的代码.

我的代码看起来像这样(同时尝试各种事情,获取我能想到的所有地区/文化):

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();

输出:

Current culture: en-DK
Current UI culture: en-US
Installed UI culture: en-US
Current region: DNK
System default LCID: 1033

如何让我的程序检测到我选择了德国?我需要调用什么方法或属性?哪些重启或缓存清除可能是必要的?

最佳答案

我在 this thread 中找到了问题的答案.

我正在使用下面的代码,正如@SanjaySingh 在该线程中所建议的那样,并且只是稍作修改。

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

可以找到geoFriendlyname 的值here .

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
}

关于c# - 在C#中,如何获取Windows 10中 "Country or region"下选中的 "Region & language"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46212746/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com