1、结构体SOFTWARE用于记录每个安装程序的具体信息
1 struct SOFTWARE 2 { 3 CString DisplayName; 4 CString Publisher; 5 CString InstallDate; 6 CString InstallLocation; 7 CString UninstStr; 8 CString DisplayVersion; 9 BOOL is64; 10 };
2、函数GetSoftList用于获取计算机上已安装程序的全部信息,接受vector<SOFTWARE>引用类型的参数,并将获取的全部信息存放在该vector中。
Windows 系统中,安装程序都可以在注册表 HKEY_LOCAL_MACHINE\SoftWare\Microsoft\Windows\CurrentVersion\Uninstall 获取。
1 void GetSoftList( std::vector<SOFTWARE> &lst, BOOL is64 ) 2 { 3 REGSAM samDesired = KEY_READ; 4 if(is64) 5 samDesired |= KEY_WOW64_64KEY; 6 7 HKEY hKey = NULL; 8 CString root_key = _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"); 9 //打开指定的注册表键 10 if( RegOpenKeyEx( HKEY_LOCAL_MACHINE, root_key, 0, samDesired, &hKey) != ERROR_SUCCESS ) 11 { 12 13 return; 14 } 15 16 DWORD cSubKeys = 0; //子键数量 17 DWORD cbMaxSubKey = 0; //子键名称的最大长度 18 DWORD retCode = RegQueryInfoKey(hKey, 0, 0, 0, &cSubKeys, &cbMaxSubKey, 0, 0, 0, 0, 0, 0); 19 20 for (int i=0; i<(int)cSubKeys; i++) 21 { 22 TCHAR achKey[MAX_PATH+1] = {0}; //子键名称 23 DWORD cbName = MAX_PATH; //子键名称的大小 24 25 //枚举子键信息 26 retCode = RegEnumKeyEx(hKey, i, achKey, &cbName, NULL, NULL, NULL, NULL); 27 if (retCode == ERROR_SUCCESS) 28 { 29 CString subkey = root_key + L"\\"; 30 subkey += achKey; 31 //给SOFTEARE结构体成员赋值,加入动态数组 32 _QuerySoft(HKEY_LOCAL_MACHINE, subkey, is64, lst); 33 } 34 } 35 36 RegCloseKey(hKey); 37 }
3、函数_QuerySoft获取结构体成员信息
1 void _QuerySoft(HKEY hKey, LPCTSTR lpSubKey, BOOL is64, std::vector<SOFTWARE> &lst) 2 { 3 CpzRegistry reg; 4 5 pzRegAccessRights pDesired = pzRAR_Read; 6 if(is64) 7 pDesired = pzRAR_Read64; 8 9 reg.OpenKey(hKey, lpSubKey, FALSE, pDesired); 10 11 SOFTWARE soft; 12 //给SOFTEARE结构体成员赋值 13 soft.DisplayName = reg.ReadString(_T("DisplayName")); 14 soft.DisplayName.Trim(); //去掉字符序列左边和右边的空格 15 soft.DisplayName.Replace(L"=",L""); 16 17 soft.UninstStr = reg.ReadString(_T("UninstallString")); 18 soft.UninstStr.Trim(); 19 20 soft.Publisher = reg.ReadString(_T("Publisher")); 21 soft.Publisher.Trim(); 22 23 soft.DisplayVersion = reg.ReadString(_T("DisplayVersion")); 24 soft.DisplayVersion.Trim(); 25 26 soft.InstallDate = reg.ReadString(_T("InstallDate")); 27 soft.InstallDate.Trim(); 28 29 soft.InstallLocation = reg.ReadString(_T("InstallLocation")); 30 soft.InstallLocation.Trim(); 31 32 soft.is64 = is64; 33 34 CString parent_name = reg.ReadString(_T("ParentDisplayName")); 35 CString parent_key = reg.ReadString(_T("ParentKeyName")); 36 37 int SystemComponent = 0; //系统组件 38 reg.ReadInt(_T("SystemComponent"), SystemComponent); 39 40 41 if(soft.DisplayName.GetLength() == 0) 42 return; 43 44 if(parent_name.GetLength() != 0 || parent_key.GetLength() != 0) 45 return; 46 47 if(SystemComponent) 48 return; 49 50 // 查找重名; 51 for(int i=0;i<(int)lst.size();i++) 52 { 53 if(lst[i].DisplayName == soft.DisplayName) 54 return; 55 } 56 57 //加入数组 58 lst.push_back(soft); 59 }