C++學習——獲取時區(qū)列表(windows) [23.08.04]

說明:初學C++,望各位大佬批評指正,感謝萬分!歡迎大家評論區(qū)留言討論各種問題;
思路:通過訪問windows的時區(qū)注冊表信息獲?。?/p>
關鍵:這三個函數的使用:RegEnumKeyEx(),RegOpenKeyEx(),RegQueryValueEx();
#include <Windows.h>
#include <iostream>
#include <string>
#include <tchar.h>
//將wstring轉換成string??
std::string wstring2string(std::wstring wstr)
{
???? std::string result;
???? //獲取緩沖區(qū)大小,并申請空間,緩沖區(qū)大小事按字節(jié)計算的??
???? int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);
???? char* buffer = new char[len + 1];
???? //寬字節(jié)編碼轉換成多字節(jié)編碼??
???? WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL);
???? buffer[len] = '\0';
???? //刪除緩沖區(qū)并返回值??
???? result.append(buffer);
???? delete[] buffer;
???? return result;
}
int main(){
???? HKEY hKey;
???? LONG result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones"), 0, KEY_READ, &hKey);
if (result != ERROR_SUCCESS){
????std::cout << "Failed to open registry key." << std::endl;
????return 1;
}
TCHAR subKeyName[256];
DWORD subKeyNameSize = 256;
DWORD index = 0;
// Redirect wcout to the file stream
// Enumerate all subkeys under the Time Zones key
while (RegEnumKeyEx(hKey, index, subKeyName, &subKeyNameSize, nullptr, nullptr, nullptr, nullptr) == ERROR_SUCCESS){
???? HKEY hSubKey;
???? // Open the subkey for reading
???? result = RegOpenKeyEx(hKey, subKeyName, 0, KEY_READ, &hSubKey);
if (result == ERROR_SUCCESS){
???? TCHAR displayName[256];
???? DWORD displayNameSize = 256;
????
???? // Read the display name of the time zone
???? result = RegQueryValueEx(hSubKey, _T("Display"), nullptr, nullptr, reinterpret_cast<LPBYTE>(displayName), &displayNameSize);
if (result == ERROR_SUCCESS){
???????? std::wcout << L"(" << subKeyName << L") " << displayName << std::endl;
???????? std::wstring output = L"(" + std::wstring(subKeyName) + L") " + displayName +L"\n";
???????? OutputDebugString(output.c_str()); // Send output to Visual Studio Output window
???? ????std::cout << wstring2string(output) << std::endl;
????????}
????????RegCloseKey(hSubKey);
????}
index++;
subKeyNameSize = 256; // Reset subKeyNameSize to its original value
????}
RegCloseKey(hKey);
return 0;
}
執(zhí)行結果如下:
