C++ statistics software USES time code samples
- 2020-04-02 02:02:21
- OfStack
// FileName: UseSoftTime.h
#pragma once
#include <vector>
struct UseTime
{
//The start time
SYSTEMTIME startTime;
//The end of time
SYSTEMTIME endTime;
//Time difference
SYSTEMTIME subTime;
};
struct UseSoftInfo
{
//The software name
CString SoftName;
//Software startup time; If the monitoring software exists before opening our software, the default startup time is the time when our software is opened
std::vector<UseTime> useTime;
//Cumulative service time
SYSTEMTIME allTime;
//Use the number
unsigned int nCount;
//state
bool bStatus;
};
class SoftTime
{
public:
//Software usage time
std::vector<UseSoftInfo> m_SoftUseTime;
private:
//Timer handler
static void CALLBACK TimerProc(HWND hWnd,UINT nMsg,UINT nTimerid,DWORD dwTime);
//Right to mention
BOOL EnableDebugPrivilege (BOOL fEnable);
//Calculated time difference
SYSTEMTIME SubTime (SYSTEMTIME t1, SYSTEMTIME t2);
//Calculate cumulative time
SYSTEMTIME AddTime (SYSTEMTIME t1, SYSTEMTIME t2);
//Determine if it is a system process
bool IsSystemProcess (LPCTSTR lpProName);
//The initialization time is 0
void InitTime (SYSTEMTIME& st);
public:
SoftTime();
~SoftTime();
public:
//Initializes the process information
void InitProcessName (void);
};
// FileName: UseSoftTime.cpp
#include "stdafx.h" //Delete this line if there is a compilation error
#include "UseSoftTime.h"
#include "TlHelp32.h"
#include "StrSafe.h"
#include "Psapi.h"
//Prevent error LNK2019
#pragma comment(lib, "psapi.lib")
//The global variable
SoftTime * g_pSoftTime = NULL;
SoftTime::SoftTime()
{
g_pSoftTime = this;
}
SoftTime::~SoftTime()
{
if (g_pSoftTime != NULL)
{
g_pSoftTime = NULL;
}
}
void CALLBACK SoftTime::TimerProc(HWND hWnd,UINT nMsg,UINT nTimerid,DWORD dwTime)
{
SoftTime * pSoftTimeInfo = (SoftTime*)g_pSoftTime;
//The process name of the current system normal process
std::vector<CString> currentProcessName;
HANDLE hProcessSnap = NULL;
HANDLE hProcessDll = NULL;
BOOL bRet = FALSE;
//Initialize dwSize to 0 or Process32First fails
PROCESSENTRY32 pe32 = {0};
MODULEENTRY32 me32;
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dwError;
LPCTSTR pszFormat = TEXT(" An error was encountered while starting the service ! %s");
if(!pSoftTimeInfo->EnableDebugPrivilege(1))
{
MessageBox(NULL, _T(" Submission failed! "), _T(" prompt "), MB_OK|MB_ICONEXCLAMATION);
}
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE)
{
dwError = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER|
FORMAT_MESSAGE_FROM_SYSTEM|
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dwError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
LPTSTR(&lpMsgBuf),
0,
NULL);
lpDisplayBuf = (LPVOID)LocalAlloc(
LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf)+lstrlen(pszFormat))*sizeof(TCHAR));
//Formatted string
StringCchPrintf(
(LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf), //The number of bytes
pszFormat,
lpMsgBuf);
CString strTemp;
strTemp.Format(TEXT(" Error code: :%d"), dwError);
::MessageBox(NULL, (LPCTSTR)lpDisplayBuf, strTemp, MB_OK|MB_ICONEXCLAMATION);
//Clean up the allocated memory
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
return;
}
pe32.dwSize = sizeof(PROCESSENTRY32);
Module32First(hProcessSnap, &me32);
if (Process32First(hProcessSnap, &pe32))
{
do
{
WCHAR path[MAX_PATH]={0};
HMODULE hModule;
HANDLE hProcess;
DWORD needed;
hProcess=OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pe32.th32ProcessID);
if (hProcess)
{
//The enumeration process
EnumProcessModules(hProcess, &hModule, sizeof(hModule), &needed);
//Gets the full path of the process
memset(path, 0, sizeof(WCHAR)*MAX_PATH);
GetModuleFileNameEx(hProcess, hModule, path, sizeof(WCHAR)*MAX_PATH);
if (!(pSoftTimeInfo->IsSystemProcess(path)))
{
std::vector<CString>::iterator iter;
bool bIsExist = false;
for (iter=currentProcessName.begin(); iter!=currentProcessName.end(); iter++)
{
if (*iter ==pe32.szExeFile)
{
bIsExist = true;
}
}
if (!bIsExist)
{
currentProcessName.push_back(pe32.szExeFile);
}
}
}
}
while (Process32Next(hProcessSnap, &pe32));
}
//Find an existing process
std::vector<UseSoftInfo>::iterator iter1;
std::vector<CString >::iterator iter2;
for (iter2=currentProcessName.begin(); iter2!=currentProcessName.end(); iter2++)
{
bool bIsExist = false;
int nIndex = 0;
for (iter1=pSoftTimeInfo->m_SoftUseTime.begin(); iter1!=pSoftTimeInfo->m_SoftUseTime.end(); iter1++, nIndex++)
{
//Existing processes that update software usage times
if (*iter2 == iter1->SoftName)
{
//Process already exists;
bIsExist = true;
if (iter1->bStatus)
{
SYSTEMTIME st;
GetLocalTime(&st);
int n = pSoftTimeInfo->m_SoftUseTime[nIndex].nCount - 1;
//pSoftTimeInfo->m_SoftUseTime[nIndex].allTime = pSoftTimeInfo->SubTime(pSoftTimeInfo->m_SoftUseTime[nIndex].useTime[n].startTime, st);
pSoftTimeInfo->m_SoftUseTime[nIndex].useTime[n].subTime = pSoftTimeInfo->SubTime(pSoftTimeInfo->m_SoftUseTime[nIndex].useTime[n].startTime, st);
std::vector<UseTime>::iterator iter;
pSoftTimeInfo->InitTime(st);
for (iter=pSoftTimeInfo->m_SoftUseTime[nIndex].useTime.begin(); iter!=pSoftTimeInfo->m_SoftUseTime[nIndex].useTime.end(); iter++)
{
st = pSoftTimeInfo->AddTime(st, iter->subTime);
}
pSoftTimeInfo->m_SoftUseTime[nIndex].allTime = st;
}
else //Open after the second time
{
pSoftTimeInfo->m_SoftUseTime[nIndex].nCount += 1;
pSoftTimeInfo->m_SoftUseTime[nIndex].bStatus = true;
UseTime useTime;
GetLocalTime(&useTime.startTime);
pSoftTimeInfo->InitTime(useTime.endTime);
pSoftTimeInfo->InitTime(useTime.subTime);
pSoftTimeInfo->m_SoftUseTime[nIndex].useTime.push_back(useTime);
}
}
}
//Newly added process
if (!bIsExist)
{
UseSoftInfo infoTemp;
UseTime useTime;
GetLocalTime(&useTime.startTime);
pSoftTimeInfo->InitTime(useTime.endTime);
pSoftTimeInfo->InitTime(useTime.subTime);
infoTemp.useTime.push_back(useTime);
infoTemp.SoftName = pe32.szExeFile;
pSoftTimeInfo->InitTime(infoTemp.allTime);
infoTemp.nCount = 1;
infoTemp.bStatus = true;
pSoftTimeInfo->m_SoftUseTime.push_back(infoTemp);
}
}
//Find the exit process
int nIndex = 0;
for (iter1=pSoftTimeInfo->m_SoftUseTime.begin(); iter1!=pSoftTimeInfo->m_SoftUseTime.end(); iter1++, nIndex++)
{
bool bIsExist = false;
for (iter2=currentProcessName.begin(); iter2!=currentProcessName.end(); iter2++)
{
if (iter1->SoftName == *iter2)
{
bIsExist = true;
}
}
//Exit process
if (!bIsExist && pSoftTimeInfo->m_SoftUseTime[nIndex].bStatus)
{
SYSTEMTIME st;
GetLocalTime(&st);
pSoftTimeInfo->m_SoftUseTime[nIndex].useTime[pSoftTimeInfo->m_SoftUseTime[nIndex].nCount-1].endTime = st;
pSoftTimeInfo->m_SoftUseTime[nIndex].useTime[pSoftTimeInfo->m_SoftUseTime[nIndex].nCount-1].subTime =
pSoftTimeInfo->SubTime(pSoftTimeInfo->m_SoftUseTime[nIndex].useTime[pSoftTimeInfo->m_SoftUseTime[nIndex].nCount-1].startTime, st);
std::vector<UseTime>::iterator iter;
pSoftTimeInfo->InitTime(st);
for (iter=pSoftTimeInfo->m_SoftUseTime[nIndex].useTime.begin(); iter!=pSoftTimeInfo->m_SoftUseTime[nIndex].useTime.end(); iter++)
{
st = pSoftTimeInfo->AddTime(st, iter->subTime);
}
//pSoftTimeInfo->m_SoftUseTime[nIndex].allTime = st;
pSoftTimeInfo->m_SoftUseTime[nIndex].bStatus = false;
}
}
//Close the privilege
pSoftTimeInfo->EnableDebugPrivilege(0);
//Close the kernel object
CloseHandle(hProcessSnap );
}
BOOL SoftTime::EnableDebugPrivilege (BOOL fEnable)
{
BOOL fOk = FALSE;
HANDLE hToken;
//Gets the access token for the process
if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES,&hToken))
{
TOKEN_PRIVILEGES tp;
tp.PrivilegeCount = 1;
//View system privilege values and return a LUID structure
LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &tp.Privileges[0].Luid);
tp.Privileges[0].Attributes = fEnable ? SE_PRIVILEGE_ENABLED : 0;
//Enable/close privileges
AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp), NULL, NULL);
fOk = (GetLastError() == ERROR_SUCCESS);
CloseHandle(hToken);
}
else
{
return 0;
}
return(fOk);
}
void SoftTime::InitProcessName (void)
{
HANDLE hProcessSnap = NULL;
HANDLE hProcessDll = NULL;
BOOL bRet = FALSE;
//Initialize dwSize to 0 or Process32First fails
PROCESSENTRY32 pe32 = {0};
MODULEENTRY32 me32;
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dwError;
LPCTSTR pszFormat = TEXT(" An error was encountered while starting the service ! %s");
if(!EnableDebugPrivilege(1))
{
MessageBox(NULL, _T(" Submission failed! "), _T(" prompt "), MB_OK|MB_ICONEXCLAMATION);
}
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE)
{
dwError = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER|
FORMAT_MESSAGE_FROM_SYSTEM|
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dwError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
LPTSTR(&lpMsgBuf),
0,
NULL);
lpDisplayBuf = (LPVOID)LocalAlloc(
LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf)+lstrlen(pszFormat))*sizeof(TCHAR));
//Formatted string
StringCchPrintf(
(LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf), //The number of bytes
pszFormat,
lpMsgBuf);
CString strTemp;
strTemp.Format(TEXT(" Error code: :%d"), dwError);
::MessageBox(NULL, (LPCTSTR)lpDisplayBuf, strTemp, MB_OK|MB_ICONEXCLAMATION);
//Clean up the allocated memory
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
return;
}
pe32.dwSize = sizeof(PROCESSENTRY32);
Module32First(hProcessSnap, &me32);
if (Process32First(hProcessSnap, &pe32))
{
do
{
WCHAR path[MAX_PATH]={0};
HMODULE hModule;
HANDLE hProcess;
DWORD needed;
hProcess=OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pe32.th32ProcessID);
if (hProcess)
{
//The enumeration process
EnumProcessModules(hProcess, &hModule, sizeof(hModule), &needed);
//Gets the full path of the process
memset(path, 0, sizeof(WCHAR)*MAX_PATH);
GetModuleFileNameEx(hProcess, hModule, path, sizeof(WCHAR)*MAX_PATH);
//Normal process
if (!IsSystemProcess(path))
{
UseSoftInfo infoTemp;
UseTime useTime;
GetLocalTime(&useTime.startTime);
InitTime(useTime.endTime);
InitTime(useTime.subTime);
infoTemp.useTime.push_back(useTime);
infoTemp.SoftName = pe32.szExeFile;
std::vector<UseSoftInfo>::iterator iter;
bool IsExist = false;
for (iter=m_SoftUseTime.begin(); iter!=m_SoftUseTime.end(); iter++)
{
if (iter->SoftName == infoTemp.SoftName)
{
IsExist = true;
}
}
if (!IsExist)
{
InitTime(infoTemp.allTime);
infoTemp.nCount = 1;
infoTemp.bStatus = true;
m_SoftUseTime.push_back(infoTemp);
}
}
}
}
while (Process32Next(hProcessSnap, &pe32));
}
//Close the privilege
EnableDebugPrivilege(0);
//Close the kernel object
CloseHandle(hProcessSnap );
//Set a timer
::SetTimer(NULL, 1, 1000, TimerProc);
}
bool SoftTime::IsSystemProcess (LPCTSTR lpProName)
{
CString strTemp(lpProName);
strTemp.MakeLower();
if (strTemp.Find(_T("windows")) != -1)
{
return true;
}
else if (strTemp == _T(""))
{
return true;
}
else if (strTemp.Find(_T("system32")) != -1)
{
return true;
}
else
{
return false;
}
}
SYSTEMTIME SoftTime::SubTime (SYSTEMTIME t1, SYSTEMTIME t2)
{
t2.wYear -= t1.wYear;
t2.wMonth -= t1.wMonth;
t2.wDay -= t1.wDay;
if (t2.wHour >= t1.wHour)
{
t2.wHour -= t1.wHour;
}
else
{
t2.wDay -= 1;
t2.wHour = 24 - t1.wHour + t2.wHour;
}
if (t2.wMinute >= t1.wMinute)
{
t2.wMinute -= t1.wMinute;
}
else
{
t2.wHour -= 1;
t2.wMinute = 60 - t1.wMinute + t2.wMinute;
}
if (t2.wSecond >= t1.wSecond)
{
t2.wSecond -= t1.wSecond;
}
else
{
t2.wMinute -= 1;
t2.wSecond = 60 - t1.wSecond + t2.wSecond;
}
return t2;
}
void SoftTime::InitTime (SYSTEMTIME& st)
{
st.wYear = 0;
st.wMonth = 0;
st.wDay = 0;
st.wHour = 0;
st.wMinute = 0;
st.wSecond = 0;
}
SYSTEMTIME SoftTime::AddTime (SYSTEMTIME t1, SYSTEMTIME t2)
{
t1.wSecond += t2.wSecond;
if (t1.wSecond >= 60)
{
t1.wSecond -= 60;
t1.wMinute += 1;
}
t1.wMinute += t2.wMinute;
if (t1.wMinute > 60)
{
t1.wMinute -= 60;
t1.wHour += 1;
}
t1.wHour += t2.wHour;
return t1;
}