.h头文件
CString GetProductVersion(LPCTSTR lpszFileName = NULL)
cpp文件头部加入version.lib
#pragma comment(lib, "Version.lib ")
功能代码
CString CGetAppVersionApp::GetProductVersion(LPCTSTR lpszFileName)
{
CString strVersion;
TCHAR szSrcfn[MAX_PATH];
if (lpszFileName == NULL)
{
if (!::GetModuleFileName(NULL, szSrcfn, sizeof(szSrcfn)))
{
printf("Function <GetModuleFileName> unsuccessful!, ErrorCode:%d\n", ::GetLastError());
return _T("Error");
}
}
else
{
lstrcpy(szSrcfn, lpszFileName);
}
if (!CFileFind().FindFile(lpszFileName))
{
printf("%s is not Exist!\n", lpszFileName);
return _T("Error");
}
BOOL bRet;
DWORD dwVerHnd = 0;
DWORD dwVerInfoSize = ::GetFileVersionInfoSize(szSrcfn, &dwVerHnd);
if (!dwVerInfoSize)
{
printf("Function <GetFileVersionInfo> unsuccessful!, ErrorCode:%d\n", ::GetLastError());
return _T("Error");
}
HANDLE hMem;
LPVOID lpvMem;
unsigned int uInfoSize = 0;
VS_FIXEDFILEINFO * pFileInfo;
hMem = ::GlobalAlloc(GMEM_MOVEABLE, dwVerInfoSize);
lpvMem = ::GlobalLock(hMem);
bRet = ::GetFileVersionInfo(szSrcfn, dwVerHnd, dwVerInfoSize, lpvMem);
if (!bRet)
{
printf("Function <GetFileVersionInfo> unsuccessful!, ErrorCode:%d\n", ::GetLastError());
return _T("Error");
}
bRet = ::VerQueryValue(lpvMem, (LPTSTR)_T("\\"), (LPVOID*)&pFileInfo, &uInfoSize);
if (!bRet)
{
printf("Function <VerQueryValue> unsuccessful!\n");
return _T("Error");
}
WORD nVer[4];
nVer[0] = HIWORD(pFileInfo->dwProductVersionMS);
nVer[1] = LOWORD(pFileInfo->dwProductVersionMS);
nVer[2] = HIWORD(pFileInfo->dwProductVersionLS);
nVer[3] = LOWORD(pFileInfo->dwProductVersionLS);
strVersion.Format(_T("%d.%d.%d.%d "), nVer[0], nVer[1], nVer[2], nVer[3]);
::GlobalUnlock(hMem);
::GlobalFree(hMem);
return strVersion;
}