获取本次开机时间和上次关机时间

#include 
#include 
#include
#include
using namespace std;
#pragma comment(lib, "winmm.lib ")

void  FileTimeToTimet(FILETIME ft, time_t* t)
{
    LONGLONG ll = 0;

    ULARGE_INTEGER ui;
    ui.LowPart = ft.dwLowDateTime;
    ui.HighPart = ft.dwHighDateTime;

    ll = ((INT64)ft.dwHighDateTime) << 32 + ft.dwLowDateTime;
    *t = (LONGLONG)(ui.QuadPart - 116444736000000000) / 10000000;


}

string GetBootTime()
{
    DWORD startMSCount;//从开机到现在的毫秒数
    startMSCount = timeGetTime();
    time_t CurSysTime, BootSysTime;
    time(&CurSysTime);
    //将开机到现在的毫秒数转换为秒数,再用当前的时间减去,获得开机时间
    BootSysTime = CurSysTime - startMSCount / 1000;
    struct tm* tm_boot;
    tm_boot = localtime(&BootSysTime);
    char bufbt[128] = { 0 };
    strftime(bufbt, 64, "%Y-%m-%d %H:%M:%S", tm_boot);
    return bufbt;
}


//获得最近一次关机时间,若为0,则失败
//返回格式为Unix时间,若需要其他格式时间请稍作修改即可
string GetLastShutdownTime()
{
    HKEY hKey;
    LONG lResult;
    time_t ShutdownTime = 0;
    LPCSTR lpSubKey = _T("SYSTEM\\CurrentControlSet\\Control\\Windows");
    lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, lpSubKey, 0, KEY_READ, &hKey);

    if (lResult != ERROR_SUCCESS)
        return "";
    FILETIME FileTime;
    DWORD dwSize;
    lResult = RegQueryValueEx(hKey, TEXT("ShutdownTime"),
        NULL, NULL, NULL, &dwSize);
    if (lResult == ERROR_SUCCESS && dwSize == sizeof(FileTime))
    {
        lResult = RegQueryValueEx(hKey, TEXT("ShutdownTime"), NULL,
            NULL, (LPBYTE)&FileTime, &dwSize);

        FileTimeToTimet(FileTime, &ShutdownTime);  //读取注册表数值,并进行格式转换

    }
    RegCloseKey(hKey);

    char bufst[128] = { 0 };
    struct tm* tm_st;
    tm_st = localtime(&ShutdownTime);
    strftime(bufst, 64, "%Y-%m-%d %H:%M:%S", tm_st);

    return bufst;
}

int main() {
    string bt;
    bt = GetBootTime();
    string st;
    st = GetLastShutdownTime();

    cout << "本次开机时间:" << bt << endl;
    cout << "上次关机时间:" << st << endl;
    system("pause");

    return 0;
}

你可能感兴趣的:(获取本次开机时间和上次关机时间)