Click here to Skip to main content
15,867,771 members
Articles / Programming Languages / C++

Getting System Local Time, Calculating UpTime, Setting an Alarm, Threading, etc.

Rate me:
Please Sign up or sign in to vote.
4.17/5 (4 votes)
6 Jan 2011CPOL1 min read 30.8K   895   17   4
Getting System Local Time, Calculating UpTime, Setting an Alarm, threading, etc.

Introduction

It shows how to calculate system up time, set an alarm, set when the system turns off itself, threading in MFC, etc.

Describing the Code

Getting System Time

It gets current time with function CTime class and calculates system up time as shown:

C++
DWORD dwD,dwH,dwM,dwS; 
CTime t = CTime::GetCurrentTime();   
CString s = t.Format(_T("%#c"));
DWORD tick = GetTickCount();
tick /= 1000;
dwD = tick / 86400;
dwH = tick / 3600;
dwM = (tick % 3600)/60;
dwS =  (tick % 3600)%60;

First declare a variable of type CTime, then use its GetCurrentTime method, and finally format the result by using "%#c" format specifier.

For getting system up time, first we call GetTickCount().

It gives the number of milliseconds that have elapsed since the system was started, up to 49.7 days, then divides it by 1000 to get seconds.

After getting elapsed seconds, we can convert them to day:hour:minute:second notation like above.

Shutting Down the System

We have 2 types of shutdown in the app.

In the first type, a time is given and it is compared to the current time forever in a thread, as soon as the comparison is true, the system is turned off.

C++
for(;;)
{
    if(m_bShutdownThread == false)
        return 0;
    GetLocalTime(&time);
    if(
        time.wHour   == m_ShutdownTime.wHour   &&
        time.wSecond == m_ShutdownTime.wSecond &&
        time.wMinute == m_ShutdownTime.wMinute 
      )
        ShutdownWindows();
}

In the second type, a time in notation of day:hour:minute:second is given and it is checked to see whether the time is elapsed in a thread as discussed in the above.

If the time is elapsed, system gets turned off.

C++
DWORD dwD,dwH,dwM,dwS; 
DWORD tick;
for(;;)
{
    if(m_bUpTimeShutdownThread == false)
        return 0;
    tick = GetTickCount();
    tick /= 1000;
    dwD = tick / 86400;
    dwH = tick / 3600;
    dwM = (tick % 3600)/60;
    dwS =  (tick % 3600)%60;
    if(m_UpTimeShutdownTime.wMinute == dwM &&
        m_UpTimeShutdownTime.wSecond == dwS &&
        m_UpTimeShutdownTime.wHour == dwH &&
        m_UpTimeShutdownTime.wDay == dwD
        )
        ShutdownWindows();
}

Alarm

In the alarm section, user gives a time, a thread will be started and the current time is compared to the given time.

If those times are equal, a sound is played with function PlaySound and the app flashes!

C++
SYSTEMTIME time;
    for(;;)
    {
        if(m_bAlarmThread == false)
            return 0;
        GetLocalTime(&time);
        if(
            time.wHour   == m_AlarmTime.wHour   &&
            time.wSecond == m_AlarmTime.wSecond &&
            time.wMinute == m_AlarmTime.wMinute 
          )
        {
            GetDlgItem(IDC_SETTURNOFF2)->EnableWindow();
            GetDlgItem(IDC_CANCELALARM)->EnableWindow(FALSE);
    
            GetDlgItem(IDC_HOUR2)->EnableWindow();
            GetDlgItem(IDC_MINUTE2)->EnableWindow();
            GetDlgItem(IDC_SECOND2)->EnableWindow();
            FlashWindowEx(FLASHW_ALL,-1,0);
            PlaySoundW(_T("alarm.wav"),
                NULL,SND_LOOP|SND_FILENAME|SND_ASYNC);
            GetDlgItem(IDC_MUTE)->EnableWindow();

            CStringW strOut;
            strOut.Format(_T(""));
            GetDlgItem(IDC_AOUT)->SetWindowTextW(strOut);

          break;
        }
    }

Some Notes

For shutting down, the app adjusts its Privilege, and the calls function ExitWindowEx()

C++
HANDLE hToken; 
TOKEN_PRIVILEGES tkp; 
OpenProcessToken(GetCurrentProcess(), 
    TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken) ; 
LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, 
        &tkp.Privileges[0].Luid); 
tkp.PrivilegeCount = 1; 
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; 
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, 
        (PTOKEN_PRIVILEGES)NULL, 0); 
ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE, 
               SHTDN_REASON_MAJOR_OPERATINGSYSTEM |
               SHTDN_REASON_MINOR_UPGRADE |
               SHTDN_REASON_FLAG_PLANNED) ;

Points of Interest

There is a lot of GUI handling code in this application, but those are unrelated to the subject, so I haven't shown them in the article.

History

  • 6th January, 2011: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
President
Iran (Islamic Republic of) Iran (Islamic Republic of)
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 3 Pin
Mahdi Nejadsahebi11-Oct-12 10:42
Mahdi Nejadsahebi11-Oct-12 10:42 
GeneralMy vote of 5 Pin
VikramRathod7-Mar-11 19:57
VikramRathod7-Mar-11 19:57 
GeneralHello Mr David ! Pin
PE32_6418-Jan-11 3:03
PE32_6418-Jan-11 3:03 
GeneralSuggestions Pin
David Crow10-Jan-11 3:41
David Crow10-Jan-11 3:41 
The article in its current format is vastly incomplete (i.e., when I got to the end, I was left scratching my head). For example, Getting System Local Time, Calculating UpTime, Setting an Alarm, and Threading are all mutually exclusive, or disparate, things. While your intent is good, you need to show and discuss how they can be tied together to accomplish some goal (i.e., what is the article's purpose).

Other suggestions:


Getting the minutes from GetTickCount() should probably be:

DWORD dwH = (tick % 86400) / 3600;


You mention threading, but no secondary threads are created. Threads are not something that you can lightly skim over. Either talk about them as they pertain to the article or don't mention them at all.

Instead of creating an unnecessary variable like:

CStringW strOut;
strOut.Format(_T(""));
GetDlgItem(IDC_AOUT)->SetWindowTextW(strOut);


you could simply use:

GetDlgItem(IDC_AOUT)->SetWindowTextW(_T(""));
Your gratuitous use of GetDlgItem() warrants the need to read this article.

"One man's wage rise is another man's price increase." - Harold Wilson

"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

"Man who follows car will be exhausted." - Confucius


General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.