C++ 通過登錄檔獲取Windows版本資訊
阿新 • • 發佈:2019-01-04
原理:通過訪問登錄檔 HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion 下的鍵值資訊來獲取windows版本資訊。由於是訪問登錄檔獲取的資訊,所以準確性一般。
#include <atlstr.h> // 使用CString類 #include <windows.h> // 預設返回系統名稱,需要的話可以自己修改 CString GetSysEdition() { HKEY hKey; DWORD dwSize = 50; // 鍵值的值長度最大值,過小會導致RegQueryValueEx()呼叫失敗 LPBYTE lpProductName = new BYTE[dwSize]; // 儲存系統名稱 LPBYTE lpEditionID = new BYTE[dwSize]; // 儲存版本ID DWORD dwDataType = REG_SZ; LPCTSTR subKey = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"; long errorCode; if (IsOn64BitSystem()) { cout << "64Bit OS" << endl; errorCode = RegOpenKeyEx(HKEY_LOCAL_MACHINE, subKey, NULL, KEY_READ | KEY_WOW64_64KEY, &hKey); } else { cout << "32Bit OS" << endl; errorCode = RegOpenKeyEx(HKEY_LOCAL_MACHINE, subKey, NULL, KEY_READ, &hKey); } if ((ERROR_SUCCESS == RegQueryValueEx(hKey, "ProductName", NULL, &dwDataType, lpProductName, &dwSize)) && (ERROR_SUCCESS == RegQueryValueEx(hKey, "EditionID", NULL, &dwDataType, lpEditionID, &dwSize)) && (ERROR_SUCCESS == errorCode)) { // 僅供參考 cout << lpProductName << endl; cout << lpEditionID << endl; } delete []lpProductName; delete []lpEditionID; RegCloseKey(hKey); return (CString)lpProductName; } // 用於判斷是否是64位系統,是則返回true,反則false bool IsOn64BitSystem() { SYSTEM_INFO sys; GetNativeSystemInfo(&sys); if (sys.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 || sys.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64) return true; else return false; }
另附上常用Windows的登錄檔版本名用於返回值判斷:
Windows 10 Home
Windows 10 Pro
Windows 10 Pro N
Windows 10 Enterprise
Windows 10 Education
Windows 10 Enterprise 2016 LTSB
Windows 8.1 Pro
Windows 8 Pro
Windows 7 Pro
Windows 7 Enterprise
Windows 7 Ultimate
水平有限,僅供參考!