#include "StdAfx.h" #include #include "Global.h" #include // 关机函数; // Jeff.获取文件版本号函数头文件; #include #pragma comment(lib,"version.lib") using namespace std; // 注册OCX bool RegOcx(CString ocxfile) #include "afxcoll.h" #include "afxtempl.h" #include "atlconv.h" // 在函数GetOSDisplayString的前面需要定义如下宏: // 同时还要包含strsafe.h #include #pragma comment(lib, "User32.lib") #include #include namespace Global { ////////////////////////////////////////////////////////////////////////// // 全局变量; TCHAR g_szHostName[MAX_PATH]; // 主机计算机名; TCHAR g_szModulePath[MAX_PATH]; // 软件目录; TCHAR g_szModuleFileName[MAX_PATH]; // 软件名称; TCHAR g_szConnectString[MAX_PATH]; // DB连接串; // 服务器信息; TCHAR g_szDBSource[MAX_PATH]; // 数据库源(服务所在IP或计算机名); TCHAR g_szDBSourcePort[MAX_PATH]; // 数据库源端口; DWORD g_dwDBServerPort; // 数据库源端口; TCHAR g_szDBAccount[MAX_PATH]; // 数据库登录用户; TCHAR g_szDBPassWord[MAX_PATH]; // 数据库登录密码; TCHAR g_szDBName[MAX_PATH]; // 数据库名称; TCHAR g_szLogDBName[MAX_PATH]; // Log数据库名称; DWORD g_dwCSPort = 5678; // 客户端与服务端的通信端口; Encryptlockkernel::YtInfoVer1 g_YtInfoVer1; #define MY_ENCODING_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING) #define KEYLENGTH 0x00800000 #define ENCRYPT_ALGORITHM CALG_RC4 #define ENCRYPT_BLOCK_SIZE 8 ////////////////////////////////////////////////////////////////////////// static const int BEGIN_YEAR = 1901; static const int NUMBER_YEAR = 199; static const unsigned int LUNAR_YEARS[199] = { 0x04AE53, 0x0A5748, 0x5526BD, 0x0D2650, 0x0D9544, 0x46AAB9, 0x056A4D, 0x09AD42, 0x24AEB6, 0x04AE4A, //1901-1910 0x6A4DBE, 0x0A4D52, 0x0D2546, 0x5D52BA, 0x0B544E, 0x0D6A43, 0x296D37, 0x095B4B, 0x749BC1, 0x049754, //1911-1920 0x0A4B48, 0x5B25BC, 0x06A550, 0x06D445, 0x4ADAB8, 0x02B64D, 0x095742, 0x2497B7, 0x04974A, 0x664B3E, //1921-1930 0x0D4A51, 0x0EA546, 0x56D4BA, 0x05AD4E, 0x02B644, 0x393738, 0x092E4B, 0x7C96BF, 0x0C9553, 0x0D4A48, //1931-1940 0x6DA53B, 0x0B554F, 0x056A45, 0x4AADB9, 0x025D4D, 0x092D42, 0x2C95B6, 0x0A954A, 0x7B4ABD, 0x06CA51, //1941-1950 0x0B5546, 0x555ABB, 0x04DA4E, 0x0A5B43, 0x352BB8, 0x052B4C, 0x8A953F, 0x0E9552, 0x06AA48, 0x7AD53C, //1951-1960 0x0AB54F, 0x04B645, 0x4A5739, 0x0A574D, 0x052642, 0x3E9335, 0x0D9549, 0x75AABE, 0x056A51, 0x096D46, //1961-1970 0x54AEBB, 0x04AD4F, 0x0A4D43, 0x4D26B7, 0x0D254B, 0x8D52BF, 0x0B5452, 0x0B6A47, 0x696D3C, 0x095B50, //1971-1980 0x049B45, 0x4A4BB9, 0x0A4B4D, 0xAB25C2, 0x06A554, 0x06D449, 0x6ADA3D, 0x0AB651, 0x093746, 0x5497BB, //1981-1990 0x04974F, 0x064B44, 0x36A537, 0x0EA54A, 0x86B2BF, 0x05AC53, 0x0AB647, 0x5936BC, 0x092E50, 0x0C9645, //1991-2000 0x4D4AB8, 0x0D4A4C, 0x0DA541, 0x25AAB6, 0x056A49, 0x7AADBD, 0x025D52, 0x092D47, 0x5C95BA, 0x0A954E, //2001-2010 0x0B4A43, 0x4B5537, 0x0AD54A, 0x955ABF, 0x04BA53, 0x0A5B48, 0x652BBC, 0x052B50, 0x0A9345, 0x474AB9, //2011-2020 0x06AA4C, 0x0AD541, 0x24DAB6, 0x04B64A, 0x69573D, 0x0A4E51, 0x0D2646, 0x5E933A, 0x0D534D, 0x05AA43, //2021-2030 0x36B537, 0x096D4B, 0xB4AEBF, 0x04AD53, 0x0A4D48, 0x6D25BC, 0x0D254F, 0x0D5244, 0x5DAA38, 0x0B5A4C, //2031-2040 0x056D41, 0x24ADB6, 0x049B4A, 0x7A4BBE, 0x0A4B51, 0x0AA546, 0x5B52BA, 0x06D24E, 0x0ADA42, 0x355B37, //2041-2050 0x09374B, 0x8497C1, 0x049753, 0x064B48, 0x66A53C, 0x0EA54F, 0x06B244, 0x4AB638, 0x0AAE4C, 0x092E42, //2051-2060 0x3C9735, 0x0C9649, 0x7D4ABD, 0x0D4A51, 0x0DA545, 0x55AABA, 0x056A4E, 0x0A6D43, 0x452EB7, 0x052D4B, //2061-2070 0x8A95BF, 0x0A9553, 0x0B4A47, 0x6B553B, 0x0AD54F, 0x055A45, 0x4A5D38, 0x0A5B4C, 0x052B42, 0x3A93B6, //2071-2080 0x069349, 0x7729BD, 0x06AA51, 0x0AD546, 0x54DABA, 0x04B64E, 0x0A5743, 0x452738, 0x0D264A, 0x8E933E, //2081-2090 0x0D5252, 0x0DAA47, 0x66B53B, 0x056D4F, 0x04AE45, 0x4A4EB9, 0x0A4D4C, 0x0D1541, 0x2D92B5 //2091-2099 }; ////////////////////////////////////////////////////////////////////////// static INT CALLBACK BrowseCallbackProc(HWND hwnd, UINT uMsg, LPARAM lp, LPARAM pData) { switch (uMsg) { case BFFM_INITIALIZED: SendMessage(hwnd, BFFM_SETSELECTION, TRUE, NULL); break; case BFFM_SELCHANGED: { TCHAR szFileName[MAX_PATH]; LPITEMIDLIST pidlCurrent = (LPITEMIDLIST)lp; SHGetPathFromIDList(pidlCurrent, szFileName); SendMessage(hwnd, BFFM_SETSTATUSTEXT, 0, (LPARAM)szFileName); } break; // 这个不能让默认目录为桌面; // case BFFM_INITIALIZED: // { // // WParam is TRUE since you are passing a path. // // It would be FALSE if you were passing a pidl. // TCHAR szDir[MAX_PATH] = { 0 }; // GetCurrentDirectory(sizeof(szDir) / sizeof(TCHAR), szDir); // SendMessage(hwnd, BFFM_SETSELECTION, TRUE, (LPARAM)szDir); // } // break; } return 0; } BOOL GetFilePath(TCHAR *FilePath, HWND hParentWnd, TCHAR* InstructionString, UINT ulFlags) { BROWSEINFO bInfo; LPITEMIDLIST pidl, pidlDesktop; ZeroMemory((PVOID)&bInfo, sizeof(BROWSEINFO)); SHGetSpecialFolderLocation(NULL, CSIDL_DESKTOP, &pidlDesktop); bInfo.pidlRoot = pidlDesktop; bInfo.hwndOwner = hParentWnd; bInfo.pszDisplayName = FilePath; bInfo.lpszTitle = InstructionString; bInfo.ulFlags = ulFlags; bInfo.lpfn = BrowseCallbackProc; bInfo.lParam = 0; if ((pidl = ::SHBrowseForFolder(&bInfo)) == NULL) return FALSE; if (::SHGetPathFromIDList(pidl, FilePath) == FALSE) return FALSE; return TRUE; } void GetHostName() { CHAR szHostName[MAX_PATH] = {0}; gethostname(szHostName,MAX_PATH); #ifdef UNICODE TCHAR *pHostName = ascii2unicode(szHostName); #else TCHAR *pHostName = szHostName; #endif _stprintf_s(g_szHostName, _T("%s"), pHostName); #ifdef UNICODE delete []pHostName; #endif } BOOL IsValidDate(IN LPCTSTR lpDate) // 判断公历; { if (lpDate == NULL || _tcscmp(lpDate, _T("")) == 0) return FALSE; CString strDate = lpDate; if (strDate.IsEmpty()) return FALSE; // 判断日期合法性; static int nYear = 0; static int nMonth = 0; static int nDay = 0; nYear = nMonth = nDay = 0; nYear = _ttoi(strDate.Left(4)); nMonth = _ttoi(strDate.Mid(5, 2)); nDay = _ttoi(strDate.Mid(8, 2)); CONST static INT nNormalMonth[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; CONST static INT nLeapMonth[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; if ((nDay <= 0) || (nDay > 31) || (nMonth <= 0) || (nMonth > 12)) return FALSE; if ((nYear % 400 == 0) || (nYear % 4 == 0 && nYear % 100 != 0)) { if (nDay > nLeapMonth[nMonth - 1]) return FALSE; } else { if (nDay > nNormalMonth[nMonth - 1]) return FALSE; } return TRUE; } BOOL IsValidLunanrDate(IN LPCTSTR lpDate) // 判断农历; { if (lpDate == NULL || _tcscmp(lpDate, _T("")) == 0) return FALSE; CString strDate = lpDate; if (strDate.IsEmpty()) return FALSE; static int lunar_year, lunar_month, lunar_day; lunar_year = lunar_month = lunar_day = 0; lunar_year = _ttoi(strDate.Left(4)); lunar_month = _ttoi(strDate.Mid(5, 2)); lunar_day = _ttoi(strDate.Mid(8, 2)); //越界检查,如果越界,返回无效日期; if (lunar_year <= BEGIN_YEAR || lunar_year > BEGIN_YEAR + NUMBER_YEAR - 1) return FALSE; if (lunar_month < 1 || lunar_month > 12) return FALSE; // 1.农历年是否有闰月; int nYearIndex = lunar_year - BEGIN_YEAR; int leap_month = (LUNAR_YEARS[nYearIndex] >> 20) & 0xF; // 2.月份大小月天数; int month_day = 0; if ((LUNAR_YEARS[nYearIndex] >> (7 + 13 - lunar_month)) & 0x1) month_day = 30; else month_day = 29; if (lunar_day < 0 || lunar_day > month_day) return FALSE; return TRUE; } TString lowercase(IN const TString &Str) { const TCHAR aazz = _T('z') - _T('Z'); TString sResult; for (TString::const_iterator it = Str.begin(); Str.end() != it; it++) { if (_T('A') <= *it && *it <= _T('Z')) sResult.append(1, *it + aazz); else sResult.append(1, *it); } return sResult; } TString uppercase(IN const TString &Str) { const TCHAR aazz = _T('z') - _T('Z'); TString sResult; for (TString::const_iterator it = Str.begin(); Str.end() != it; it++) { if (_T('a') <= *it && *it <= _T('z')) sResult.append(1, *it - aazz); else sResult.append(1, *it); } return sResult; } int match(IN CONST TString &sFileExt, IN CONST TString &sFile) { TString fext = uppercase(sFileExt); TString file = uppercase(sFile); int pos = file.find_last_of(_T('.')); if (TString::npos != pos) file = file.substr(pos); return (TString::npos != fext.find(file)); } TString getfilename(IN CONST TString &file) { TString name; TString strfile = file; int nIndex = strfile.find_last_of(_T('\\')); // 如果file不包含 '\\' ,得不到文件名; if (nIndex == TString::npos) { nIndex = strfile.find_last_of(_T('.')); if ( nIndex == TString::npos ) return _T(""); return strfile.substr(0, nIndex); } name = strfile.substr(nIndex+1); nIndex = name.find_last_of(_T('.')); if (nIndex == TString::npos) return _T(""); return name.substr(0, nIndex); } // 获取文件名; CString getfilename(IN CONST CString &file) { CString name; CString strfile = file; int nIndex = strfile.ReverseFind(_T('\\')); // 如果file不包含 '\\' ,得不到文件名; if (nIndex == -1) { nIndex = strfile.ReverseFind(_T('.')); if (nIndex == -1) return _T(""); return strfile.Left(nIndex); } name = strfile.Mid(nIndex+1); nIndex = name.Find(_T('.')); if (nIndex == -1) return _T(""); return name.Left(nIndex); } int GetIniInfo(IN const TCHAR *szPath , const TCHAR *szIniName ) { TCHAR szDrive[_MAX_DRIVE]; TCHAR szDir[_MAX_DIR]; ::GetModuleFileName(NULL, g_szModulePath, sizeof(g_szModulePath) / sizeof(TCHAR)); _stprintf_s(g_szModulePath, MAX_PATH, _T("%s"), g_szModulePath); _tsplitpath(g_szModulePath, szDrive, szDir, NULL, NULL); _tcscpy_s(g_szModulePath, szDrive); _tcscat_s(g_szModulePath, szDir); // -----------------------------------------------------// TCHAR szIniPath[MAX_PATH] = {0}; if (szPath != NULL && szIniName != NULL) _stprintf_s(szIniPath, _T("%s%s"), szPath, szIniName); else _stprintf_s(szIniPath, _T("%sServiceInfo.ini"), g_szModulePath); HANDLE hFile = CreateFile(szIniPath, 0/*GENERIC_READ*/, 0, NULL, OPEN_EXISTING, 0, NULL); if (ERROR_FILE_NOT_FOUND == GetLastError()) { return -1; } // 获取服务器端信息; GetPrivateProfileString(_T("DatabaseInfo"), _T("dbSource"), _T(""), g_szDBSource, MAX_PATH, szIniPath); g_dwDBServerPort = GetPrivateProfileInt(_T("DatabaseInfo"), _T("dbServerPort"), 0, szIniPath); GetPrivateProfileString(_T("DatabaseInfo"), _T("dbAccount"), _T(""), g_szDBAccount, MAX_PATH, szIniPath); GetPrivateProfileString(_T("DatabaseInfo"), _T("dbPassWord"), _T(""), g_szDBPassWord, MAX_PATH, szIniPath); GetPrivateProfileString(_T("DatabaseInfo"), _T("dbName"), _T(""), g_szDBName, MAX_PATH, szIniPath); g_dwCSPort = GetPrivateProfileInt(_T("NetWorkInfo"), _T("TCPChatPort"), 5678, szIniPath); if (g_dwDBServerPort != 0) _stprintf_s(g_szConnectString, MAX_PATH, _T("driver={SQL Server};Server=%s,%d;database=%s;uid=%s;pwd=%s"), g_szDBSource, g_dwDBServerPort, g_szDBName, g_szDBAccount, g_szDBPassWord); else _stprintf_s(g_szConnectString, MAX_PATH, _T("driver={SQL Server};Server=%s;database=%s;uid=%s;pwd=%s"), g_szDBSource, g_szDBName, g_szDBAccount, g_szDBPassWord); return 0; } void GetDirveInfo() { UINT DiskType; size_t szAllDriveStrings = GetLogicalDriveStrings(0, NULL); TCHAR *pDriveStrings = new TCHAR[szAllDriveStrings + sizeof(_T(" "))]; GetLogicalDriveStrings(szAllDriveStrings, pDriveStrings); size_t szDriveString = _tcslen(pDriveStrings); while (szDriveString > 0) { AfxMessageBox(pDriveStrings); DiskType = GetDriveType(pDriveStrings); switch (DiskType) { case DRIVE_NO_ROOT_DIR: return; case DRIVE_REMOVABLE: ::AfxMessageBox(_T("移动存储设备 ")); break; case DRIVE_FIXED: ::AfxMessageBox(_T("固定硬盘驱动器 ")); break; case DRIVE_REMOTE: ::AfxMessageBox(_T("这是网络驱动器 ")); break; case DRIVE_CDROM: ::AfxMessageBox(_T("这是光盘驱动器 ")); break; } pDriveStrings += szDriveString + 1; szDriveString = _tcslen(pDriveStrings); } } BOOL OpenFloder(IN CStringArray &vtFiles, IN LPCTSTR lpFilter ) { // 获取桌面路径; TCHAR szDesktop[MAX_PATH]; SHGetSpecialFolderPath(0, szDesktop, CSIDL_DESKTOPDIRECTORY, 0); CString strFindFile = _T(""); LPTSTR lpszFile = (TCHAR*)(CONST TCHAR*)strFindFile; //LPTSTR lpszFilter = _T("图片 (*.jpg)|*.jpg|图片 (*.jpeg)|*.jpeg|图片 (*.raw)|*.raw|图片 (*.cr2)|*.cr2|图片 (*.nef)|*.nef|所有文件 (*.*)|*.*||"); LPTSTR lpszFilter = _T("图片 (*.jpg;*.jpeg;*.raw;*.cr2;*.nef)||所有文件 (*.*)|*.*||"); DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_ALLOWMULTISELECT | OFN_ENABLESIZING; CFileDialog dlg(TRUE, _T("default Files (*.jpg)"), NULL, dwFlags, lpszFilter, NULL); dlg.m_ofn.lpstrTitle = _T("请选择要导入的图片"); // 显示的标题, 应该做成参数传入; dlg.m_ofn.lpstrInitialDir = szDesktop; // 默认打开的文件夹, 应该做成参数传入; // 最多可以打开nMaxFile个文件 // 注意,这里的nMaxFile其实不是真正的个数,而是lpstrFile数组的长度,每个文件最大长度为MAX_PATH,所以个数是n*MAX_PATH; dlg.m_ofn.nMaxFile = 1500 * MAX_PATH; dlg.m_ofn.lpstrFile = new TCHAR[dlg.m_ofn.nMaxFile]; ZeroMemory(dlg.m_ofn.lpstrFile, sizeof(TCHAR) * dlg.m_ofn.nMaxFile); // 显示文件对话框,获得文件名集合; if (dlg.DoModal() == IDCANCEL) { delete[]dlg.m_ofn.lpstrFile; dlg.m_ofn.lpstrFile = NULL; return FALSE; } POSITION pos_file = dlg.GetStartPosition(); while (pos_file != NULL) vtFiles.Add((LPCTSTR)dlg.GetNextPathName(pos_file)); // 释放内存; delete[]dlg.m_ofn.lpstrFile; dlg.m_ofn.lpstrFile = NULL; return TRUE; } BOOL OpenFloder(IN STR_VEC &vtFiles, IN LPCTSTR lpFilter) { // 获取桌面路径; TCHAR szDesktop[MAX_PATH]; SHGetSpecialFolderPath(0, szDesktop, CSIDL_DESKTOPDIRECTORY, 0); CString strFindFile = _T(""); LPTSTR lpszFile = (TCHAR*)(CONST TCHAR*)strFindFile; //LPTSTR lpszFilter = _T("图片 (*.jpg)|*.jpg|图片 (*.jpeg)|*.jpeg|图片 (*.raw)|*.raw|图片 (*.cr2)|*.cr2|图片 (*.nef)|*.nef|所有文件 (*.*)|*.*||"); LPTSTR lpszFilter = _T("图片 (*.jpg;*.jpeg;*.raw;*.cr2;*.nef)||所有文件 (*.*)|*.*||"); DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_ALLOWMULTISELECT | OFN_ENABLESIZING; CFileDialog dlg(TRUE, _T("default Files (*.jpg)"), NULL, dwFlags, lpszFilter, NULL); dlg.m_ofn.lpstrTitle = _T("请选择要导入的图片"); // 显示的标题, 应该做成参数传入; dlg.m_ofn.lpstrInitialDir = szDesktop; // 默认打开的文件夹, 应该做成参数传入; // 最多可以打开nMaxFile个文件 // 注意,这里的nMaxFile其实不是真正的个数,而是lpstrFile数组的长度,每个文件最大长度为MAX_PATH,所以个数是n*MAX_PATH; dlg.m_ofn.nMaxFile = 1500 * MAX_PATH; dlg.m_ofn.lpstrFile = new TCHAR[dlg.m_ofn.nMaxFile]; ZeroMemory(dlg.m_ofn.lpstrFile, sizeof(TCHAR) * dlg.m_ofn.nMaxFile); // 显示文件对话框,获得文件名集合; if (dlg.DoModal() == IDCANCEL) { delete[]dlg.m_ofn.lpstrFile; dlg.m_ofn.lpstrFile = NULL; return FALSE; } POSITION pos_file = dlg.GetStartPosition(); while (pos_file != NULL) vtFiles.push_back((LPCTSTR)dlg.GetNextPathName(pos_file)); // 释放内存; delete[]dlg.m_ofn.lpstrFile; dlg.m_ofn.lpstrFile = NULL; return TRUE; } // 判断指定字符串是否在数组里(区分大小写); BOOL IsStringExist(IN CString& str, IN CStringArray &tagAry) { int nSize = tagAry.GetSize(); if (nSize == 0) return FALSE; BOOL bExist = FALSE; for (int i = 0; i < nSize; i++) { if (str == tagAry.ElementAt(i)) { bExist = TRUE; break; } } return bExist; } // 判断指定字符串是否在数组里(区分大小写); BOOL IsStringExist(IN TString& str, IN STR_VEC &tagVt) { int nSize = tagVt.size(); if (nSize == 0) return FALSE; BOOL bExist = FALSE; for (STR_VEC::iterator it = tagVt.begin(); it != tagVt.end(); it++) { if (str.compare(it->c_str()) == 0) { bExist = TRUE; break; } } return bExist; } // 判断指定字符串是否在数组里(不区分大小写); BOOL IsStringExistNoCase(IN CString& str, IN CStringArray &tagAry) { int nSize = tagAry.GetSize(); if (nSize == 0) return FALSE; BOOL bExist = FALSE; for (int i = 0; i < nSize; i++) { if (str.CompareNoCase(tagAry.ElementAt(i)) == 0) { bExist = TRUE; break; } } return bExist; } // 判断指定字符串是否在数组里(不区分大小写); BOOL IsStringExistNoCase(IN CONST TString& str, IN STR_VEC &tagVt) { int nSize = tagVt.size(); if (nSize == 0) return FALSE; BOOL bExist = FALSE; TString stmp1 = uppercase(str); TString stmp2; for (STR_VEC::iterator it = tagVt.begin(); it != tagVt.end(); it++) { stmp2 = uppercase(*it); if (stmp1.compare(stmp2) == 0) { bExist = TRUE; break; } } return bExist; } /************************************************************************/ /* 函数:IsValidpath 描述:判断一个路径是否是本地可以盘符或可用的网络路径; 参数: IN: strPath 要判断的路径; 返回:盘符或网络路径有效返回TRUE; */ /************************************************************************/ BOOL IsValidpath(IN CONST TString &strPath) { // 文件表现形式有三种: // 1.本地形式: C:\myfolder\you // 2.共享形式: \\192.168.1.112\myfolder\\you if (strPath.size() < 2) return FALSE; // 含":"为本地路径; if (strPath[1] == _T(':')) { DWORD dwDiskType = 0; dwDiskType = GetDriveType(strPath.substr(0, 3).c_str()); switch (dwDiskType) { case DRIVE_UNKNOWN: // 未知驱动盘符; case DRIVE_NO_ROOT_DIR: // 没有根目录; //case DRIVE_REMOVABLE: // 移动存储设备盘符; // case DRIVE_FIXED: // 硬盘; case DRIVE_CDROM: // CD盘符; case DRIVE_RAMDISK: // ; return FALSE; break; } } else if (strPath.substr(0, 2).find(_T("\\\\")) != TString::npos) { // 共享路径; TString strtmp = strPath.substr(2); int n = strPath.substr(2).find(_T("\\")); if (n == TString::npos) return FALSE; strtmp = strPath.substr(0, n + 2); // 需要判断网络路径可用否; DWORD dwRet = 0; NETRESOURCE nr; memset(&nr, 0, sizeof(nr)); nr.dwScope = RESOURCE_CONNECTED; nr.dwType = RESOURCETYPE_ANY; nr.dwDisplayType = RESOURCEDISPLAYTYPE_GENERIC; nr.dwUsage = RESOURCEUSAGE_CONNECTABLE; #ifndef UNICODE nr.lpRemoteName = (LPSTR)strtmp.c_str(); #else nr.lpRemoteName = (LPWSTR)(strtmp.c_str()); #endif dwRet = WNetAddConnection2(&nr, NULL, NULL, CONNECT_UPDATE_PROFILE); if (dwRet == ERROR_BAD_NETPATH)// 无效的网络路径,表示没有这个网络地址; return FALSE; else if (dwRet == ERROR_LOGON_FAILURE)// 登陆这个网络路径失败,因为当前用户名和密码错误; 没有权限; return FALSE; } return TRUE; } void Splitpath(IN CONST TCHAR *path, IN TCHAR * drive, IN size_t driveNumberOfElements, IN TCHAR * dir, IN size_t dirNumberOfElements, IN CONST int &nTimes) { int i = 0; int npoint = 0; // '.' int nsprit = 0; // '\\' int ncolon = 0; // ':' int ntimes = -1; #ifdef UNICODE // 使用_tcslen来代替wcslen和strlen有问题,在UNICODE时还没有问题,一但转成多字节后_tcslen就不准确; int nlen = wcslen(path); #else int nlen = strlen(path); #endif while (nlen > i++) { if (path[i] == _T(':')) ncolon = i; else if (path[i] == _T('\\')) { nsprit = i; if (nTimes == ++ntimes) break; } } //memcpy_s(drive, driveNumberOfElements*sizeof(TCHAR), path, (ncolon + 1)*sizeof(TCHAR)); //memcpy_s(dir, dirNumberOfElements*sizeof(TCHAR), &path[ncolon + 1], (nsprit - ncolon)*sizeof(TCHAR)); #ifdef UNICODE wmemcpy_s(drive, driveNumberOfElements, path, ncolon + 1); wmemcpy_s(dir, dirNumberOfElements, &path[ncolon + 1], nsprit - ncolon); #else memcpy_s(drive, driveNumberOfElements, path, ncolon + 1); memcpy_s(dir, dirNumberOfElements, &path[ncolon + 1], nsprit - ncolon); #endif } /************************************************************************/ /* 函数:全局函数JCreateDirectory,多字节版本,支持UNICODE 描述:创建目录及子目录文件夹; 参数: lpDestDirectory:目录,必须是"E:\lyfzdb\数据\"格式,目录最后必须有"\",否则最后一个子目录无法创建! 建议使用系统_tsplitpath来分隔目录,这样会保存最后一个"\"斜杠; 返回:成功创建返回TRUE; */ /************************************************************************/ BOOL CreateDirectoryEx(IN LPCTSTR lpNewDirectory) { // 判断路径有效性 if (!lpNewDirectory || !IsValidpath(lpNewDirectory)) return FALSE; BOOL bExists = FALSE; TCHAR szNewFileName[_MAX_PATH] = { 0 }; TCHAR szDrive[_MAX_DRIVE] = { 0 }; TCHAR szDir[_MAX_DIR] = { 0 }; TCHAR szFna[_MAX_FNAME] = { 0 }; TCHAR szExt[_MAX_EXT] = { 0 }; TCHAR szNewDirectory[_MAX_PATH] = { 0 }; if (lpNewDirectory[_tcslen(lpNewDirectory) - 1] != _T('\\')) StringCchPrintf(szNewDirectory, _MAX_PATH, _T("%s\\"), lpNewDirectory); else StringCchPrintf(szNewDirectory, _MAX_PATH, _T("%s"), lpNewDirectory); int nIndex = 0; do { bExists = PathFileExists(szNewDirectory); if (!bExists) { memset(szDrive, 0, _MAX_DRIVE*sizeof(TCHAR)); memset(szDir, 0, _MAX_DIR*sizeof(TCHAR)); memset(szFna, 0, _MAX_FNAME*sizeof(TCHAR)); memset(szExt, 0, _MAX_EXT*sizeof(TCHAR)); Splitpath(szNewDirectory, szDrive, _MAX_DRIVE, szDir, _MAX_DIR, ++nIndex); StringCchPrintf(szNewFileName, _MAX_PATH, _T("%s%s"), szDrive, szDir); if (!CreateDirectory(szNewFileName, NULL)) { DWORD dwError = GetLastError(); switch (dwError) { case ERROR_PATH_NOT_FOUND: // 路径未找到,上一层目录未创建导致该错误; case ERROR_ACCESS_DENIED: // 没有权限访问; case ERROR_BAD_NET_NAME: // 错误的网络名称; //case ERROR_BAD_PATHNAME: // return FALSE; break; case ERROR_ALREADY_EXISTS: // 文件存在,不需要创建; break; default: break; } } } } while (!bExists); return TRUE; } /************************************************************************/ /* 函数:GetDiskSpaceInfo 描述:获取指定目录或盘符的容量信息; 参数: IN: lpRootPathName 根目录名称; INOUT: dTotalNum 总容量; INOUT: dFreeNum 可用容量; 返回: 注意: GetDiskFreeSpace函数不能满足当前超过2T的硬盘容量,因为里面的数据类型是UINT,最大支持32位(4G); GetDiskFreeSpaceEx支持64位(16384P=1024*16384T) 能获取本机硬盘信息,但路径必须包含":"冒号, 同时还可以获取网络路径的共享硬盘大小; 调用约定: */ /************************************************************************/ BOOL GetDiskSpaceInfo(IN LPCTSTR lpRootPathName, IN OUT double &dTotalNum, IN OUT double &dFreeNum) { #if 1 // 校验参数有效性; if (lpRootPathName == NULL || _tcscmp(lpRootPathName, _T("")) == 0) { //_tprintf_s(_T("根目录为空!")); return FALSE; } // 如果长度==1; int nlen = _tcslen(lpRootPathName); if ((1 == nlen) || (2 == nlen && lpRootPathName[nlen - 1] != _T(':'))) { //_tprintf_s(_T("根目录无效!\n")); return FALSE; } if (!PathFileExists(lpRootPathName)) { //_tprintf_s(_T("根目录不存在!\n")); return FALSE; } #else // 使用IsValipath判断网络路径时较慢; if (!IsValidpath(lpRootPathName) || !PathFileExists(lpRootPathName)) return FALSE; #endif BOOL fResult = FALSE; DWORD dwSectPerClust; // 每簇的扇区数; DWORD dwBytesPerSect; // 每个扇区的字节数; DWORD dwFreeClusters; // 可用簇数; DWORD dwTotalClusters; // 总簇数; typedef BOOL(WINAPI *P_GDFSE)(LPCTSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER); P_GDFSE pGetDiskFreeSpaceEx = NULL; /*unsigned*/ __int64 i64FreeBytesToCaller; /*unsigned*/ __int64 i64TotalBytes; /*unsigned*/ __int64 i64FreeBytes; // 调用GetDiskFreeSpaceEx失败则调用GetDiskSpace; #ifdef UNICODE pGetDiskFreeSpaceEx = (P_GDFSE)GetProcAddress(GetModuleHandle(_T("kernel32.dll")), "GetDiskFreeSpaceExW"); #else pGetDiskFreeSpaceEx = (P_GDFSE)GetProcAddress(GetModuleHandle("kernel32.dll"), "GetDiskFreeSpaceExA"); #endif if (pGetDiskFreeSpaceEx) { fResult = pGetDiskFreeSpaceEx(lpRootPathName, (PULARGE_INTEGER)&i64FreeBytesToCaller, (PULARGE_INTEGER)&i64TotalBytes, (PULARGE_INTEGER)&i64FreeBytes); if (fResult) { // 将单位由byte转为G byte; dTotalNum = (double)i64TotalBytes / 1024 / 1024 / 1024; dFreeNum = (double)i64FreeBytes / 1024 / 1024 / 1024; } } else { fResult = GetDiskFreeSpace(lpRootPathName, &dwSectPerClust, &dwBytesPerSect, &dwFreeClusters, &dwTotalClusters); if (fResult) { // 成功获得容量信息; i64TotalBytes = (__int64)dwTotalClusters * dwSectPerClust * dwBytesPerSect; i64FreeBytes = (__int64)dwFreeClusters * dwSectPerClust * dwBytesPerSect; // 将单位由byte转为G byte; dTotalNum = (double)i64TotalBytes / 1024 / 1024 / 1024; dFreeNum = (double)i64FreeBytes / 1024 / 1024 / 1024; } } return fResult; } // 通过路径名查找进程,返回进程ID; BOOL FindAppProcessID(IN CString path, OUT DWORD &dwProcessID) { int nIndex = path.ReverseFind('\\'); path = path.Right(path.GetLength() - nIndex - 1); dwProcessID = FindProcess(path); return (dwProcessID != 0 ? TRUE : FALSE); BOOL bFound = FALSE; HANDLE handle = ::CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0); PROCESSENTRY32 Info; Info.dwSize = sizeof(PROCESSENTRY32); path.MakeLower(); if (::Process32First(handle, &Info)) { do{ CString ss = Info.szExeFile; ss.MakeLower(); if (ss == path) { ::CloseHandle(handle); dwProcessID = Info.th32ProcessID; bFound = TRUE; break; } } while (::Process32Next(handle, &Info)); if (handle) ::CloseHandle(handle); } return (bFound ? TRUE : FALSE); } // 根据路径名查找进程,返回进程ID; DWORD FindProcess(IN CString strProName) { DWORD dwProcessID = 0; PROCESSENTRY32 pe32 = { 0 }; HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hProcessSnap == NULL) { return 0; } pe32.dwSize = sizeof(PROCESSENTRY32); if (Process32First(hProcessSnap, &pe32)) { do { if (_tcscmp(strProName.GetBuffer(), pe32.szExeFile) == 0) { dwProcessID = pe32.th32ProcessID; break; } } while (Process32Next(hProcessSnap, &pe32)); } CloseHandle(hProcessSnap); return dwProcessID; } // 根据路径名查找进程,查找成功并结束; int FindAndCloseProcess(IN CString strProName) { int nIndex = strProName.ReverseFind('\\'); if (nIndex != -1) // 如果传的是全路径; strProName = strProName.Right(strProName.GetLength() - nIndex - 1); DWORD dwProcessID = 0; PROCESSENTRY32 pe32 = { 0 }; HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hProcessSnap == NULL) { return 0; } pe32.dwSize = sizeof(PROCESSENTRY32); if (Process32First(hProcessSnap, &pe32)) { do { if (_tcscmp(strProName.GetBuffer(), pe32.szExeFile) == 0) { dwProcessID = pe32.th32ProcessID; break; } } while (Process32Next(hProcessSnap, &pe32)); } CloseHandle(hProcessSnap); if (dwProcessID == 0) return 0; HANDLE hProcess = ::OpenProcess(PROCESS_ALL_ACCESS, TRUE, dwProcessID); if (hProcess == NULL) return 0; DWORD dwError; if (!TerminateProcess(hProcess, 0)) { dwError = GetLastError(); CloseHandle(hProcess); return -1; } // 等待进程结束响应; if (WAIT_OBJECT_0 != WaitForSingleObject(hProcess, INFINITE)) { CloseHandle(hProcess); AfxMessageBox(_T("结束进程失败")); return -1; } CloseHandle(hProcess); return 1; } // Jeff.Hacker. WINDOWS NT 以上的内核需要提权,才能对系统进行高级管理; BOOL GetDebugPriv() { // 返回的访问令牌指针; HANDLE hToken; // 接收所返回的制定特权名称的信息; LUID sedebugnameValue; // 新特权信息的指针(结构体); TOKEN_PRIVILEGES tkp; DWORD dwCurProcId = GetCurrentProcessId(); // 要修改访问权限的进程句柄; HANDLE hCurProc; hCurProc = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwCurProcId); if (!::OpenProcessToken(hCurProc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) { ShowSystemErrorInfo(_T("升级包OpenProcessToken失败."),GetLastError()); return FALSE; } if (!::LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &sedebugnameValue)) { ShowSystemErrorInfo(_T("升级包LookupPrivilegeValue失败."),GetLastError()); CloseHandle(hToken); return FALSE; } tkp.PrivilegeCount = 1; tkp.Privileges[0].Luid = sedebugnameValue; tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if (!::AdjustTokenPrivileges(hToken, FALSE, &tkp, sizeof tkp, NULL, NULL)) { ShowSystemErrorInfo(_T("升级包AdjustTokenPrivileges失败."),GetLastError()); CloseHandle(hToken); return FALSE; } CloseHandle(hCurProc); CloseHandle(hToken); return TRUE; } bool GetFileVersion(HMODULE hModule, WORD *pBuffer) { TCHAR fname[MAX_PATH]; VS_FIXEDFILEINFO *pVi; DWORD dwHandle; if (::GetModuleFileName(hModule, fname, MAX_PATH)) { int size = GetFileVersionInfoSize(fname, &dwHandle); if (size > 0) { BYTE *buffer = new BYTE[size]; memset(buffer, 0, size); if (GetFileVersionInfo(fname, dwHandle, size, buffer)) { if (VerQueryValue(buffer, _T("\\"), (LPVOID *)&pVi, (PUINT)&size)) { pBuffer[0] = HIWORD(pVi->dwFileVersionMS); pBuffer[1] = LOWORD(pVi->dwFileVersionMS); pBuffer[2] = HIWORD(pVi->dwFileVersionLS); pBuffer[3] = LOWORD(pVi->dwFileVersionLS); delete[]buffer; return true; } } delete[]buffer; } } return false; } bool GetProductVersion(HMODULE hModule, WORD *pBuffer) { TCHAR fname[MAX_PATH]; VS_FIXEDFILEINFO *pVi; DWORD dwHandle; if (::GetModuleFileName(hModule, fname, MAX_PATH)) { int size = GetFileVersionInfoSize(fname, &dwHandle); if (size > 0) { BYTE *buffer = new BYTE[size]; memset(buffer, 0, size); if (GetFileVersionInfo(fname, dwHandle, size, buffer)) { if (VerQueryValue(buffer, _T("\\"), (LPVOID *)&pVi, (PUINT)&size)) { pBuffer[0] = HIWORD(pVi->dwProductVersionMS); pBuffer[1] = LOWORD(pVi->dwProductVersionMS); pBuffer[2] = HIWORD(pVi->dwProductVersionLS); pBuffer[3] = LOWORD(pVi->dwProductVersionLS); delete[]buffer; return true; } } delete[]buffer; } } return false; } /************************************************************************/ /* 目标:HKEY_LOCAL_MACHINE\SOFTWARE\CLASSES\WOW6432NODE\CLSID\{AC5D0DDE-BD4C-11D1-B137-0000F8753F5D}\INPROCSERVER32\[] 目标:HKEY_LOCAL_MACHINE\SOFTWARE\CLASSES\WOW6432NODE\CLSID\{3A2B370C-BA0A-11D1-B137-0000F8753F5D}\INPROCSERVER32\[] */ /************************************************************************/ //---------------------------------------------------------- // 函数:RegisterOcx // 描述:注册指定的组件文件; // 参数:ocxfile指定要注册的组件文件名; // 返回:TRUE表示注册成功; //---------------------------------------------------------- BOOL RegisterOcx(LPCTSTR ocxfile) { HKEY hKey; bool bRet; USES_CONVERSION; ITypeLib* pTypeLib; CString CLSIDStr; CLSID clsid; LPOLESTR wRes = NULL; if (LoadTypeLib(T2OLE(const_cast(ocxfile)), &pTypeLib) == S_OK) { TLIBATTR tlibAttr, *ptlibAttr; ptlibAttr = &tlibAttr; pTypeLib->GetLibAttr(&ptlibAttr); clsid = ptlibAttr->guid; pTypeLib->Release(); } ::StringFromCLSID(clsid, &wRes); CLSIDStr = OLE2CT(wRes); if ((RegOpenKeyEx(HKEY_CLASSES_ROOT, _T("CLSID\\") + CLSIDStr, 0, KEY_READ, &hKey) == ERROR_SUCCESS) || (RegOpenKeyEx(HKEY_CLASSES_ROOT, _T("Wow6432Node\\TypeLib\\") + CLSIDStr, 0, KEY_READ, &hKey) == ERROR_SUCCESS)) { return true; } else { HINSTANCE hLib = LoadLibrary(ocxfile); if (hLib < (HINSTANCE)HINSTANCE_ERROR) { MessageBox(0, _T("权限不足,不能载入OCX文件!无法注册控件!"), _T("结果"), MB_OK); bRet = false; } else { FARPROC lpDllEntryPoint; //lpDllEntryPoint = GetProcAddress(hLib, _T("DllRegisterServer")); lpDllEntryPoint = GetProcAddress(hLib, "DllRegisterServer"); if (lpDllEntryPoint != NULL) { if (FAILED((*lpDllEntryPoint)())) { MessageBox(0, _T("调用注册函数(DllRegisterServer)失败!无法注册控件!"), _T("结果"), MB_OK); bRet = false; } else bRet = true; } else { MessageBox(0, _T("调用注册函数(DllRegisterServer)失败!无法注册控件!"), _T("结果"), MB_OK); bRet = false; } } FreeLibrary(hLib); return bRet; } } //-------------------------------------------------------------------------------- // Jeff add 2014.06.23; // 函数:ErrorExit // 描述: // 参数: // lpszFunction:函数名; // dwError:错误码; // //-------------------------------------------------------------------------------- void ShowSystemErrorInfo(CString strDescription, const DWORD &dwError) { #if 1 LPVOID lpMsgBuf; BOOL fOk = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL); if (!fOk) { // Is it a network-related error? HMODULE hDll = LoadLibraryEx(TEXT("netmsg.dll"), NULL, DONT_RESOLVE_DLL_REFERENCES); if (hDll != NULL) { FormatMessage( FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, hDll, dwError, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (LPTSTR)&lpMsgBuf, 0, NULL); FreeLibrary(hDll); } } if (lpMsgBuf != NULL) { CString strDisplay; strDisplay.Format(_T("%s.错误码=%d,Windows描述:%s"), strDescription, dwError, (PCTSTR)LocalLock(lpMsgBuf)); //WriteLog(strDisplay); LocalFree(lpMsgBuf); } else { //WriteLog(strDescription); } #else HLOCAL hlocal = NULL; // Buffer that gets the error message string // Get the error code's textual description BOOL fOk = FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwError, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (PTSTR)&hlocal, 0, NULL); if (!fOk) { // Is it a network-related error? HMODULE hDll = LoadLibraryEx(TEXT("netmsg.dll"), NULL, DONT_RESOLVE_DLL_REFERENCES); if (hDll != NULL) { FormatMessage( FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, hDll, dwError, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (PTSTR)&hlocal, 0, NULL); FreeLibrary(hDll); } } if (hlocal != NULL) { CString strDisplay; strDisplay.Format("%s 失败错误码=%d,Windows系统描述:%s", strDescription, dwError, (PCTSTR)LocalLock(hlocal)); //WriteLog(strDisplay); LocalFree(hlocal); } else { //WriteLog("Error number not found."); } #endif } // The system displays a dialog box with a custom message and a message to the user to close applications within the specified time-out interval (30 seconds). // After the time-out interval elapses, the system is restarted. //The application must enable the SE_SHUTDOWN_NAME privilege before calling InitiateSystemShutdown BOOL MySystemShutdown(LPTSTR lpMsg) { HANDLE hToken; // handle to process token TOKEN_PRIVILEGES tkp; // pointer to token structure BOOL fResult; // system shutdown flag // Get the current process token handle so we can get shutdown // privilege. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) return FALSE; // Get the LUID for shutdown privilege. LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid); tkp.PrivilegeCount = 1; // one privilege to set tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; // Get shutdown privilege for this process. AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0); // Cannot test the return value of AdjustTokenPrivileges. if (GetLastError() != ERROR_SUCCESS) return FALSE; // Display the shutdown dialog box and start the countdown. fResult = InitiateSystemShutdown( NULL, // shut down local computer lpMsg, // message for user 30, // time-out period, in seconds FALSE, // ask user to close apps TRUE); // reboot after shutdown if (!fResult) return FALSE; // Disable shutdown privilege. tkp.Privileges[0].Attributes = 0; AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0); return TRUE; } // If the AbortSystemShutdown function is executed in the time-out period specified by InitiateSystemShutdown, // the system does not shut down. For example, if PreventSystemShutdown is called after MySystemShutdown, // the system closes the dialog box and does not restart the system. BOOL PreventSystemShutdown() { HANDLE hToken; // handle to process token TOKEN_PRIVILEGES tkp; // pointer to token structure // Get the current process token handle so we can get shutdown // privilege. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) return FALSE; // Get the LUID for shutdown privilege. LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid); tkp.PrivilegeCount = 1; // one privilege to set tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; // Get shutdown privilege for this process. AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0); if (GetLastError() != ERROR_SUCCESS) return FALSE; // Prevent the system from shutting down. if (!AbortSystemShutdown(NULL)) return FALSE; // Disable shutdown privilege. tkp.Privileges[0].Attributes = 0; AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0); return TRUE; } // Shutting down flushes file buffers to disk and brings the system to a condition in which it is safe to turn off the computer // The application must first enable the SE_SHUTDOWN_NAME privilege. // The final parameter in the call to ExitWindowsEx indicates that the system was shut down for a planning update of the operating system. BOOL MySystemShutdown() { HANDLE hToken; TOKEN_PRIVILEGES tkp; // Get a token for this process. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) return(FALSE); // Get the LUID for the shutdown privilege. LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid); tkp.PrivilegeCount = 1; // one privilege to set tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; // Get the shutdown privilege for this process. AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0); if (GetLastError() != ERROR_SUCCESS) return FALSE; // Shut down the system and force all applications to close. if (!ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE, SHTDN_REASON_MAJOR_OPERATINGSYSTEM | SHTDN_REASON_MINOR_UPGRADE | SHTDN_REASON_FLAG_PLANNED)) return FALSE; return TRUE; } //---------------------------------------------------------- // 函数:CheckInternalIP // 描述:判断IP(网络字节序)地址是否为外网地址; // 参数:ip_addr:主机IP(必须为网络字节序); // // 返回:TRUE表示主机IP为外网IP; FALSE表示内网IP; // IP地址转为化DWORD是32位二进制; // 每8位一个点十进制; //---------------------------------------------------------- BOOL IsInternalIPV4(const unsigned int &ip_addr) { // 三段保留IP段,做为私有地址,不在在公网上使用,只作内网IP; // A类:10.0.0.0 ~ 10.255.255.255 = 0A.00.00.00 ~ 0A.FF.FF.FF // B类:172.16.0.0 ~ 172.31.255.255 = AC.10.00.00 ~ AC.1F.FF.FF // C类:192.168.0.0 ~ 192.168.255.255 = C0.A8.00.00 ~ C0.A8.FF.FF // D类:127.0.0.0 ~ 127.255.255.255 = 7F.00.00.00 ! 7F.FF.FF.FF (环回地址) // //检查3类地址是否属于公网; // (ip_addr >= 0x0A000000 && ip_addr <= 0x0AFFFFFF) || // (ip_addr >= 0xAC100000 && ip_addr <= 0xAC1FFFFF) || // (ip_addr >= 0xC0A80000 && ip_addr <= 0xC0A8FFFF) // // 检查3类地址是否属于内网; // 0xa -- "10.0.0.0">>24; // 0xc0a8--"192.168.0.0.">>16; // 0x2b0--"127.17.0.1">>22 // D类: "127.0.0.1~127.254.254.254" >> 0x7 // 回环地址也算进去! if ((ip_addr >> 24 == 0x0A) || (ip_addr >> 20 == 0xAC1) || (ip_addr >> 16 == 0xC0A8) || (ip_addr >> 26 == 0x7F)) return FALSE; else return TRUE; } // 获取指定主机名的IPV4地址; VC 6.0不适合使用本函数; // 只适用于VS2010以下版本编译器; INT GetHostIPV4( OUT vector& vtHostIPV4 ) { WSADATA wsa = {0}; if ( 0 != WSAStartup(MAKEWORD(2, 2),&wsa) ) return -1; CHAR szHostName[MAX_PATH] = {0}; gethostname(szHostName,MAX_PATH); DWORD dwHostIP = 0; PHOSTENT hostinfo = gethostbyname(szHostName); if ( hostinfo == NULL ) return -1; in_addr addr = {0}; LPCSTR hostip; while(*(hostinfo->h_addr_list) != NULL) // IPV4 { //struct in_addr ad = *(struct in_addr *) *hostinfo->h_addr_list; hostip = inet_ntoa(*(struct in_addr *) *hostinfo->h_addr_list); // InetNtop instead; DWORD dwIP = inet_addr(hostip); if ( IsInternalIPV4(dwIP) ) { #ifdef UNICODE WCHAR *psz = ascii2unicode(hostip); vtHostIPV4.push_back(psz); delete []psz; #else vtHostIPV4.push_back(hostip); #endif } hostinfo->h_addr_list++; } return 0; } // 应用于V14编译平台; // 使用GetAddrInfo; INT GetHostIPV4_V14(OUT vector& vtHostIPV4) { return 0; } INT get_ip() { struct addrinfo *ailist, *aip; struct addrinfo hint; struct sockaddr_in6 *sinp6; PHOSTENT hostinfo; char hostname[255] = {0}; //主机名 char *port = "3294"; //端口号 const char *addr; int ilRc; gethostname(hostname, sizeof(hostname)); if((hostinfo = gethostbyname(hostname)) == NULL) //获得本地ipv4地址 { errno = GetLastError(); fprintf(stderr,"gethostbyname Error:%d\n", errno); return 1; } LPCSTR ip; while(*(hostinfo->h_addr_list) != NULL) //输出ipv4地址 { ip = inet_ntoa(*(struct in_addr *) *hostinfo->h_addr_list); printf("ipv4 addr = %s\n\n", ip); hostinfo->h_addr_list++; } hint.ai_family = AF_INET6; /* hint 的限定设置 */ hint.ai_socktype = SOCK_STREAM; /* 这里可是设置 socket type 比如 SOCK——DGRAM */ hint.ai_flags = AI_PASSIVE; // flags 的标志很多 。常用的有AI_CANONNAME; hint.ai_protocol = 0; /* 设置协议 一般为0,默认 */ hint.ai_addrlen = 0; /* 下面不可以设置,为0,或者为NULL */ hint.ai_canonname = NULL; hint.ai_addr = NULL; hint.ai_next = NULL; ilRc = getaddrinfo(hostname, port, &hint, &ailist); /*通过主机名获得地址信息*/ if (ilRc < 0) { char str_error[100]; strcpy_s(str_error, (char *)gai_strerror(errno)); printf("str_error = %s", str_error); return 0; } if(ailist == NULL) { printf("sorry not find the IP address,please try again \n"); } for (aip = ailist; aip != NULL; aip = aip->ai_next) /* 显示获取的信息 */ { aip->ai_family = AF_INET6; sinp6 = (struct sockaddr_in6 *)aip->ai_addr; /* 为什么是for 循环 ,先向下看 */ int i; printf("ipv6 addr = "); for(i = 0; i < 16; i++) { if(((i-1)%2) && (i>0)) { printf(":"); } printf("%02x",sinp6->sin6_addr.u.Byte[i]); } printf(" \n"); printf(" \n"); } while(1); } BOOL EncryptFile2(BYTE *buffer, DWORD leng, PCHAR szPassword) { try { HCRYPTPROV hCryptProv; HCRYPTKEY hKey; HCRYPTHASH hHash; PBYTE pbBuffer; DWORD dwBlockLen; DWORD dwBufferLen; DWORD dwCount; //以下获得一个CSP句柄 if (CryptAcquireContext( &hCryptProv, NULL, //NULL表示使用默认密钥容器,默认密钥容器名为用户登陆名 NULL, PROV_RSA_FULL, 0)) { printf("A cryptographic provider has been acquired. \n"); } else//密钥容器不存在 { if (CryptAcquireContext( &hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET))//创建密钥容器 { //创建密钥容器成功,并得到CSP句柄 printf("A new key container has been created.\n"); } else { return 0; } } //-------------------------------------------------------------------- // 创建一个会话密钥(session key) // 会话密钥也叫对称密钥,用于对称加密算法。 // (注: 一个Session是指从调用函数CryptAcquireContext到调用函数 // CryptReleaseContext 期间的阶段。) //-------------------------------------------------------------------- // Create a hash object. if (CryptCreateHash( hCryptProv, CALG_MD5, 0, 0, &hHash)) { printf("A hash object has been created. \n"); } else { return 0; } //-------------------------------------------------------------------- // 用输入的密码产生一个散列 if (CryptHashData( hHash, (BYTE *)szPassword, strlen(szPassword), 0)) { printf("The password has been added to the hash. \n"); } else { return 0; } //-------------------------------------------------------------------- // 通过散列生成会话密钥(session key) if (CryptDeriveKey( hCryptProv, ENCRYPT_ALGORITHM, hHash, KEYLENGTH, &hKey)) { printf("An encryption key is derived from the password hash. \n"); } else { return 0; } //-------------------------------------------------------------------- // Destroy the hash object. CryptDestroyHash(hHash); hHash = NULL; //-------------------------------------------------------------------- // The session key is now ready. //-------------------------------------------------------------------- // 因为加密算法是按ENCRYPT_BLOCK_SIZE 大小的块加密的,所以被加密的 // 数据长度必须是ENCRYPT_BLOCK_SIZE 的整数倍。下面计算一次加密的 // 数据长度。 dwBlockLen = 1000 - 1000 % ENCRYPT_BLOCK_SIZE; //-------------------------------------------------------------------- // Determine the block size. If a block cipher is used, // it must have room for an extra block. if (ENCRYPT_BLOCK_SIZE > 1) dwBufferLen = dwBlockLen + ENCRYPT_BLOCK_SIZE; else dwBufferLen = dwBlockLen; dwCount = dwBufferLen; //-------------------------------------------------------------------- // In a do loop, encrypt the source file and write to the source file. int count; // if(leng%dwBlockLen==0) count = leng / dwBufferLen; // else // count=leng/dwBlockLen+1; int i = 0; for ( i = 0; i < count; i++) { pbBuffer = buffer + i*dwBufferLen; // 加密数据 if (!CryptEncrypt( hKey, //密钥 0, //如果数据同时进行散列和加密,这里传入一个散列对象 0, //如果是最后一个被加密的块,输入TRUE.如果不是输入FALSE. //这里通过判断是否到文件尾来决定是否为最后一块。 0, //保留 pbBuffer, //输入被加密数据,输出加密后的数据 &dwCount, //输入被加密数据实际长度,输出加密后数据长度 dwBufferLen)) //pbBuffer的大小。 { return 0; } } if (leng%dwBlockLen) { pbBuffer = buffer + i*dwBufferLen; dwCount = leng - i*dwBufferLen; if (!CryptEncrypt( hKey, //密钥 0, //如果数据同时进行散列和加密,这里传入一个散列对象 TRUE, //如果是最后一个被加密的块,输入TRUE.如果不是输入FALSE. //这里通过判断是否到文件尾来决定是否为最后一块。 0, //保留 pbBuffer, //输入被加密数据,输出加密后的数据 &dwCount, //输入被加密数据实际长度,输出加密后数据长度 dwBufferLen)) //pbBuffer的大小。 { return 0; } } //-------------------------------------------------------------------- // Destroy session key. if (hKey) CryptDestroyKey(hKey); //-------------------------------------------------------------------- // Destroy hash object. if (hHash) CryptDestroyHash(hHash); //-------------------------------------------------------------------- // Release provider handle. if (hCryptProv) CryptReleaseContext(hCryptProv, 0); return(TRUE); } catch (...) { } } // 是否运行在Wow64下;XP SP2以上系统才支持; BOOL IsWow64() { typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS)(HANDLE, PBOOL); LPFN_ISWOW64PROCESS fnIsWow64Process; BOOL bIsWow64 = FALSE; fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process"); if (NULL != fnIsWow64Process) { if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64)) { // 句柄错误,则系统不是64位; AfxMessageBox(_T("句柄错误")); } } return bIsWow64; } // 2.判断系统是64位还是32位; BOOL IsOSVerIs64() { BOOL bOSVerIs64 = FALSE; SYSTEM_INFO si; PGNSI pGNSI; pGNSI = (PGNSI)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetNativeSystemInfo"); if (NULL != pGNSI) pGNSI(&si); else GetSystemInfo(&si); if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 || si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64) { bOSVerIs64 = TRUE; } return bOSVerIs64; } // 判断进程是否运行在Wow64下; INT IsWow64Process(HANDLE hprocess) { typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS)(HANDLE, PBOOL); LPFN_ISWOW64PROCESS fnIsWow64Process; INT nRet = 0; BOOL bIsWow64 = FALSE; fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process"); if (NULL != fnIsWow64Process) { if (!fnIsWow64Process(hprocess, &bIsWow64)) { // 句柄错误; AfxMessageBox(_T("句柄错误")); DWORD dwError = GetLastError(); return -1; } } return bIsWow64 ? 1 : 0; } INT GetNativeSystemInfo(OSVerInfo &tagOSInfo) { OSVERSIONINFOEX osvi; SYSTEM_INFO si; PGNSI pGNSI; BOOL bOsVersionInfoEx; ZeroMemory(&si, sizeof(SYSTEM_INFO)); ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); // Try calling GetVersionEx using the OSVERSIONINFOEX structure. // If that fails, try using the OSVERSIONINFO structure. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if (!(bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *)&osvi))) { osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if (!GetVersionEx((OSVERSIONINFO *)&osvi)) return FALSE; } // Call GetNativeSystemInfo if supported // or GetSystemInfo otherwise. pGNSI = (PGNSI)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetNativeSystemInfo"); if (NULL != pGNSI) pGNSI(&si); else GetSystemInfo(&si); TCHAR szWindowsDescription[MAX_PATH] = { 0 }; CString str; CString strWindows; switch (osvi.dwPlatformId) { case VER_PLATFORM_WIN32_NT: if (osvi.dwMajorVersion == 10) // Windows10或Windows Server预览版; { if (osvi.dwMinorVersion == 0) { if (osvi.wProductType == VER_NT_WORKSTATION) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Windows 10 ")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Windows Server Technical Preview ")); } } if (osvi.dwMajorVersion == 6) // Windows Vista ~ Windows 8.1 { if (osvi.dwMinorVersion == 3) { if (osvi.wProductType == VER_NT_WORKSTATION) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Windows 8.1 ")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Windows Server 2012 R2 ")); } if (osvi.dwMinorVersion == 2) { if (osvi.wProductType == VER_NT_WORKSTATION) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Windows 8 ")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Windows Server 2012 ")); } if (osvi.dwMinorVersion == 1) { if (osvi.wProductType == VER_NT_WORKSTATION) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Windows 7 ")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Windows Server 2008 R2 ")); } if (osvi.dwMinorVersion == 0) { if (osvi.wProductType == VER_NT_WORKSTATION) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Windows Vista ")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Windows Server 2008 ")); } } if (osvi.dwMajorVersion == 5) { if (osvi.dwMinorVersion == 2) { if (GetSystemMetrics(SM_SERVERR2) != 0) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Windows Server 2003 R2 ")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Windows Server 2003 ")); if (osvi.wSuiteMask & VER_SUITE_WH_SERVER) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Windows Home Server ")); if ((osvi.wProductType == VER_NT_WORKSTATION) && (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Windows XP Professional x64 Edition ")); } if (osvi.dwMinorVersion == 1) { StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Windows XP ")); } if (osvi.dwMinorVersion == 0) { StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Windows 2000 ")); } } if (osvi.dwMajorVersion <= 4) { StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Windows NT ")); } // Test for specific product on Windows NT 4.0 SP6 and later. // 获取Windows NT 4.0 SP6之后的版本; if (bOsVersionInfoEx) { // Test for the workstation type. if (osvi.wProductType == VER_NT_WORKSTATION && si.wProcessorArchitecture != PROCESSOR_ARCHITECTURE_AMD64) { if (osvi.dwMajorVersion == 4) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Workstation 4.0 ")); else if (osvi.wSuiteMask & VER_SUITE_PERSONAL) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Home Edition ")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Professional ")); } // Test for the server type. else if (osvi.wProductType == VER_NT_SERVER || osvi.wProductType == VER_NT_DOMAIN_CONTROLLER) { if (osvi.dwMajorVersion == 6) { if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64) { if (osvi.wSuiteMask & VER_SUITE_DATACENTER) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Datacenter Edition for Itanium-based Systems")); else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Enterprise Edition for Itanium-based Systems")); } else if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) { if (osvi.wSuiteMask & VER_SUITE_DATACENTER) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Datacenter x64 Edition ")); else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Enterprise x64 Edition ")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Standard x64 Edition ")); } else { if (osvi.wSuiteMask & VER_SUITE_DATACENTER) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Datacenter Edition ")); else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Enterprise Edition ")); else if (osvi.wSuiteMask & VER_SUITE_BLADE) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Web Edition ")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Standard Edition ")); } } else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) { if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64) { if (osvi.wSuiteMask & VER_SUITE_DATACENTER) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Datacenter Edition for Itanium-based Systems")); else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Enterprise Edition for Itanium-based Systems")); } else if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) { if (osvi.wSuiteMask & VER_SUITE_DATACENTER) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Datacenter x64 Edition ")); else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Enterprise x64 Edition ")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Standard x64 Edition ")); } else { if (osvi.wSuiteMask & VER_SUITE_DATACENTER) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Datacenter Edition ")); else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Enterprise Edition ")); else if (osvi.wSuiteMask & VER_SUITE_BLADE) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Web Edition ")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Standard Edition ")); } } else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) { if (osvi.wSuiteMask & VER_SUITE_DATACENTER) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Datacenter Server ")); else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Advanced Server ")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Server ")); } else if (osvi.dwMajorVersion == 4) // Windows NT 4.0 { if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Server 4.0, Enterprise Edition ")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Server 4.0 ")); } } } // Test for specific product on Windows NT 4.0 SP5 and earlier else { HKEY hKey; TCHAR szProductType[BUFSIZE]; DWORD dwBufLen = BUFSIZE*sizeof(TCHAR); LONG lRet; lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("SYSTEM\\CurrentControlSet\\Control\\ProductOptions"), 0, KEY_QUERY_VALUE, &hKey); if (lRet != ERROR_SUCCESS) return FALSE; lRet = RegQueryValueEx(hKey, TEXT("ProductType"), NULL, NULL, (LPBYTE)szProductType, &dwBufLen); RegCloseKey(hKey); if ((lRet != ERROR_SUCCESS) || (dwBufLen > BUFSIZE*sizeof(TCHAR))) return FALSE; if (lstrcmpi(TEXT("WINNT"), szProductType) == 0) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Workstation ")); if (lstrcmpi(TEXT("LANMANNT"), szProductType) == 0) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Server ")); if (lstrcmpi(TEXT("SERVERNT"), szProductType) == 0) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Advanced Server ")); //printf( "%d.%d ", osvi.dwMajorVersion, osvi.dwMinorVersion ); } // Display service pack (if any) and build number. if (osvi.dwMajorVersion == 4 && lstrcmpi(osvi.szCSDVersion, TEXT("Service Pack 6")) == 0) { HKEY hKey; LONG lRet; // Test for SP6 versus SP6a. lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009"), 0, KEY_QUERY_VALUE, &hKey); if (lRet == ERROR_SUCCESS) str.Format(_T("Service Pack 6a (Build %d)"), osvi.dwBuildNumber & 0xFFFF); else // Windows NT 4.0 prior to SP6a { str.Format(_T("%s (Build %d)"), osvi.szCSDVersion, osvi.dwBuildNumber & 0xFFFF); } RegCloseKey(hKey); } else // not Windows NT 4.0 { str.Format(_T("%s (Build %d)"), osvi.szCSDVersion, osvi.dwBuildNumber & 0xFFFF); } StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, str); break; // Test for the Windows Me/98/95. case VER_PLATFORM_WIN32_WINDOWS: if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) { StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Windows 95 ")); if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B') StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("OSR2 ")); } if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) { StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Windows 98 ")); if (osvi.szCSDVersion[1] == 'A' || osvi.szCSDVersion[1] == 'B') StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("SE ")); } if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90) { StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Windows Millennium Edition")); } break; case VER_PLATFORM_WIN32s: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, _T("Microsoft Win32s")); break; } AfxMessageBox(strWindows); return 0; } BOOL GetSystemInfo(OSVerInfo &tagOSInfo) { OSVERSIONINFOEX osvi; SYSTEM_INFO si; PGNSI pGNSI; PGPI pGPI; BOOL bOsVersionInfoEx; DWORD dwType; ZeroMemory(&si, sizeof(SYSTEM_INFO)); ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if (!(bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *)&osvi))) { osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if (!GetVersionEx((OSVERSIONINFO *)&osvi)) return FALSE; } pGNSI = (PGNSI)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetNativeSystemInfo"); if (NULL != pGNSI) pGNSI(&si); else GetSystemInfo(&si); tagOSInfo.dwMajorVersion = osvi.dwMajorVersion; tagOSInfo.dwMinorVersion = osvi.dwMinorVersion; tagOSInfo.wProductType = osvi.wProductType; if (VER_PLATFORM_WIN32_NT == osvi.dwPlatformId && osvi.dwMajorVersion > 4) { StringCchCopy(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Microsoft ")); // Test for the specific product. if (osvi.dwMajorVersion == 10) { if (osvi.dwMinorVersion == 0) { if (osvi.wProductType == VER_NT_WORKSTATION) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Windows 10 ")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Windows Server Technical Preview ")); } pGPI = (PGPI)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetProductInfo"); pGPI(osvi.dwMajorVersion, osvi.dwMinorVersion, 0, 0, &dwType); switch (dwType) { case PRODUCT_ULTIMATE: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Ultimate Edition")); break; case PRODUCT_HOME_PREMIUM: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Home Premium Edition")); break; case PRODUCT_HOME_BASIC: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Home Basic Edition")); break; case PRODUCT_ENTERPRISE: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Enterprise Edition")); break; case PRODUCT_BUSINESS: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Business Edition")); break; case PRODUCT_STARTER: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Starter Edition")); break; case PRODUCT_CLUSTER_SERVER: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Cluster Server Edition")); break; case PRODUCT_DATACENTER_SERVER: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Datacenter Edition")); break; case PRODUCT_DATACENTER_SERVER_CORE: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Datacenter Edition (core installation)")); break; case PRODUCT_ENTERPRISE_SERVER: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Enterprise Edition")); break; case PRODUCT_ENTERPRISE_SERVER_CORE: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Enterprise Edition (core installation)")); break; case PRODUCT_ENTERPRISE_SERVER_IA64: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Enterprise Edition for Itanium-based Systems")); break; case PRODUCT_SMALLBUSINESS_SERVER: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Small Business Server")); break; case PRODUCT_SMALLBUSINESS_SERVER_PREMIUM: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Small Business Server Premium Edition")); break; case PRODUCT_STANDARD_SERVER: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Standard Edition")); break; case PRODUCT_STANDARD_SERVER_CORE: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Standard Edition (core installation)")); break; case PRODUCT_WEB_SERVER: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Web Server Edition")); break; } } if (osvi.dwMajorVersion == 6) { if (osvi.dwMinorVersion == 0) { if (osvi.wProductType == VER_NT_WORKSTATION) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Windows Vista ")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Windows Server 2008 ")); } if (osvi.dwMinorVersion == 1) { if (osvi.wProductType == VER_NT_WORKSTATION) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Windows 7 ")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Windows Server 2008 R2 ")); } if (osvi.dwMinorVersion == 2) { if (osvi.wProductType == VER_NT_WORKSTATION) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Windows 8 ")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Windows Server 2012 ")); } if (osvi.dwMinorVersion == 3) { if (osvi.wProductType == VER_NT_WORKSTATION) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Windows 8.1 ")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Windows Server 2012 R2 ")); } pGPI = (PGPI)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetProductInfo"); pGPI(osvi.dwMajorVersion, osvi.dwMinorVersion, 0, 0, &dwType); switch (dwType) { case PRODUCT_ULTIMATE: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Ultimate Edition")); break; case PRODUCT_HOME_PREMIUM: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Home Premium Edition")); break; case PRODUCT_HOME_BASIC: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Home Basic Edition")); break; case PRODUCT_ENTERPRISE: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Enterprise Edition")); break; case PRODUCT_BUSINESS: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Business Edition")); break; case PRODUCT_STARTER: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Starter Edition")); break; case PRODUCT_CLUSTER_SERVER: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Cluster Server Edition")); break; case PRODUCT_DATACENTER_SERVER: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Datacenter Edition")); break; case PRODUCT_DATACENTER_SERVER_CORE: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Datacenter Edition (core installation)")); break; case PRODUCT_ENTERPRISE_SERVER: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Enterprise Edition")); break; case PRODUCT_ENTERPRISE_SERVER_CORE: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Enterprise Edition (core installation)")); break; case PRODUCT_ENTERPRISE_SERVER_IA64: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Enterprise Edition for Itanium-based Systems")); break; case PRODUCT_SMALLBUSINESS_SERVER: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Small Business Server")); break; case PRODUCT_SMALLBUSINESS_SERVER_PREMIUM: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Small Business Server Premium Edition")); break; case PRODUCT_STANDARD_SERVER: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Standard Edition")); break; case PRODUCT_STANDARD_SERVER_CORE: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Standard Edition (core installation)")); break; case PRODUCT_WEB_SERVER: StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Web Server Edition")); break; } } if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) { if (GetSystemMetrics(SM_SERVERR2)) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Windows Server 2003 R2, ")); else if (osvi.wSuiteMask == VER_SUITE_STORAGE_SERVER) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Windows Storage Server 2003")); else if (osvi.wSuiteMask == VER_SUITE_WH_SERVER) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Windows Home Server")); else if (osvi.wProductType == VER_NT_WORKSTATION && si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) { StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Windows XP Professional x64 Edition")); } else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Windows Server 2003, ")); // Test for the server type. if (osvi.wProductType != VER_NT_WORKSTATION) { if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64) { if (osvi.wSuiteMask & VER_SUITE_DATACENTER) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Datacenter Edition for Itanium-based Systems")); else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Enterprise Edition for Itanium-based Systems")); } else if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) { if (osvi.wSuiteMask & VER_SUITE_DATACENTER) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Datacenter x64 Edition")); else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Enterprise x64 Edition")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Standard x64 Edition")); } else { if (osvi.wSuiteMask & VER_SUITE_COMPUTE_SERVER) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Compute Cluster Edition")); else if (osvi.wSuiteMask & VER_SUITE_DATACENTER) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Datacenter Edition")); else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Enterprise Edition")); else if (osvi.wSuiteMask & VER_SUITE_BLADE) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Web Edition")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Standard Edition")); } } } if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) { StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Windows XP ")); if (osvi.wSuiteMask & VER_SUITE_PERSONAL) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Home Edition")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Professional")); } if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) { StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Windows 2000 ")); if (osvi.wProductType == VER_NT_WORKSTATION) { StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Professional")); } else { if (osvi.wSuiteMask & VER_SUITE_DATACENTER) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Datacenter Server")); else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Advanced Server")); else StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT("Server")); } } // Include service pack (if any) and build number. if (_tcslen(osvi.szCSDVersion) > 0) { StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT(" ")); StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, osvi.szCSDVersion); } TCHAR buf[80]; StringCchPrintf(buf, 80, TEXT(" (build %d)"), osvi.dwBuildNumber); StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, buf); if (osvi.dwMajorVersion >= 6) { if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 || si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64) { tagOSInfo.bIs64Bit = TRUE; StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT(", 64-bit")); } else if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL) { tagOSInfo.bIs64Bit = FALSE; StringCchCat(tagOSInfo.szOSVerName, BUFSIZE, TEXT(", 32-bit")); } } return TRUE; } else { _tprintf(_T("This sample does not support this version of Windows.\n")); return FALSE; } } };