Reading the regional location setting (country code) in Windows using Ruby?

馋奶兔 提交于 2019-12-02 07:37:33

问题


I am trying to access the Control Panel: Region and Language: Location: Current location setting using Ruby. I am only interested in the country code.

The closest I have got is the country code from the System Locale but that is not quite what I was after.

`systeminfo | findstr /B /C:"System Locale"`.to_s.upcase.strip[30..31]

I hope that someone out there might know. Thanks.


回答1:


Using the Win32 API:

require 'Win32API'

# Set up some Win32 constants
GEOCLASS_NATION  = 16
GEO_ISO2         = 4
GEO_FRIENDLYNAME = 8

# Set up some API calls
GetUserGeoID = Win32API.new('kernel32', 'GetUserGeoID', ['L'], 'L')
GetGeoInfo   = Win32API.new('kernel32', 'GetGeoInfoA', ['L', 'L', 'P', 'L', 'L'], 'L')

# Get user's GEOID
geoid = GetUserGeoID.call(GEOCLASS_NATION)
=> 77

# Get ISO name
buffer = " " * 100
GetGeoInfo.call(geoid, GEO_ISO2, buffer, buffer.length, 0)
geo_iso = buffer.strip
=> "FI"

# Get friendly name
buffer = " " * 100
GetGeoInfo.call(geoid, GEO_FRIENDLYNAME, buffer, buffer.length, 0)
geo_name = buffer.strip
=> "Finland"

Documentation for GetUserGeoID:
http://msdn.microsoft.com/en-us/library/dd318138.aspx

Documentation for GetGeoInfo:
https://docs.microsoft.com/en-us/windows/desktop/api/winnls/nf-winnls-getgeoinfoa

To convert a GEOID to a location name you can also use this table:
http://msdn.microsoft.com/en-us/library/dd374073.aspx



来源:https://stackoverflow.com/questions/10621985/reading-the-regional-location-setting-country-code-in-windows-using-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!