EQuestionAnswers.com Computer/Electronics Questions and Answers
C, C++, VC++, COM/DCOM, DLL and more
#Login #Sign up  Facebook Twitter TGoogle+
 

#Previous question #Index of VC++/WIN32/MFC Questions #Next question

Timer Events

Timer events are handled by Win32 framework and Windows operating system. Application can register one or more timer events with corresponding timer identities. Orerating system periodically calls the timer event as per interval given. This is handled in the task manager part of the kernel. SetTimer() is the Win32 function to register a timer event and KillTimer() can be used to stop the timer. Application written in MFC can use CWnd::SetTimer() and CWnd::KillTimer() member functions of CWnd.

SetTimer() API can be called with proper argument to set a timer routine with defined time interval. There are two possible way to set a timer for an application.

  • Set an event identifier associated with a window handle. This will set a timer to be called by posting a WM_TIMER event to the window procedure WndProc().
  • Set a timer call back function TimerProc() with an event id. Timer call back will be fired with specified time interval.

SetTimer

The SetTimer function creates a timer with the specified time-out value.

UINT SetTimer(
  HWND hWnd,
  UINT nIDEvent,
  UINT uElapse, 
  TIMERPROC lpTimerFunc 
);

Parameters

  • hWnd - Handle to the window to be associated with the timer. This window must be owned by the calling thread. If this parameter is NULL, no window is associated with the timer and the nIDEvent parameter is ignored.
  • nIDEvent - Specifies a nonzero timer identifier. If the hWnd parameter is NULL, this parameter is ignored.
  • uElapse - Specifies the time-out value, in milliseconds.
  • lpTimerFunc - Pointer to the function to be notified when the time-out value elapses. For more information about the function, see TimerProc. If lpTimerFunc is NULL, the system posts a WM_TIMER message to the application queue. The hwnd member of the message's MSG structure contains the value of the hWnd parameter.

Return Values

If the function succeeds, the return value is an integer identifying the new timer. An application can pass this value, or the string identifier, if it exists, to the KillTimer function to destroy the timer.
If the function fails to create a timer, the return value is zero.

TimerProc callback function

An application-defined callback function that processes WM_TIMER messages. The TIMERPROC type defines a pointer to this callback function. TimerProc is a placeholder for the application-defined function name.

Syntax

VOID CALLBACK TimerProc(HWND hwnd, UINT uMsg, UINT idEvent,  DWORD dwTime);

Parameters

  • hwnd - A handle to the window associated with the timer.
  • uMsg - The WM_TIMER message.
  • idEvent - The timer's identifier.
  • dwTime - The number of milliseconds that have elapsed since the system was started. This is the value returned by the GetTickCount function.

Return value

This function does not return a value.

KillTimer

Destroys the specified timer.

Syntax

BOOL WINAPI KillTimer(HWND hWnd, UINT uIDEvent);

Parameters

  • hWnd - A handle to the window associated with the specified timer. This value must be the same as the hWnd value passed to the SetTimer function that created the timer.
  • uIDEvent - The timer to be destroyed. If the window handle passed to SetTimer is valid, this parameter must be the same as the nIDEvent value passed to SetTimer. If the application calls SetTimer with hWnd set to NULL, this parameter must be the timer identifier returned by SetTimer.

Return value

If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.

Sample demo

Below is a small demo application to show the utility of SetTimer() and KillTimer(). This application creates a top level window. On clicking left mouse button it sets the timer and on clicking right button it kills the timer. In timer event we are taking latest time from system and display it in the title bar. The timer has a value of one second interval thus it updates like a clock. This program uses a timer proc by default when USE_TIMER_PROC macro is defined. Otherwise it uses normal windowproc and WM_TIMER message.

#include <windows.h>
#include <time.h>
#define USE_TIMER_PROC
#define MY_TIMERID1 100
#define MY_TIMERID2 101
#ifdef USE_TIMER_PROC
10  VOID __stdcall MyTimerProc(HWND hWnd, UINT uMsg, UINT idEvent, DWORD dwTime)
11  {
12    time_t rawtime;
13    struct tm * timeinfo;
14    char buffer [80];
15    if (WM_TIMER == uMsg) {
16      if(idEvent == MY_TIMERID2) {
17        time (&rawtime);
18        timeinfo = localtime (&rawtime);
19        strftime (buffer,80,"Now time is %I:%M:%S%p.",timeinfo);
20        SetWindowText(hWnd, buffer);
21      }
22    }
23  }
24  #endif
25  LRESULT CALLBACK WndProc(HWND hWnd,
26                           UINT message, 
27                           WPARAM wParam,
28                           LPARAM lParam);
29 
30  int APIENTRY WinMain(HINSTANCE hInstance,
31                       HINSTANCE hPrevInstance,
32                       LPSTR     lpCmdLine,
33                       int       nCmdShow)
34  {
35    WNDCLASS wc;
36    MSG msg;
37    HWND hWnd;
38    ZeroMemory(&wc, sizeof(WNDCLASS));
39 
40    wc.style           = CS_HREDRAW | CS_VREDRAW;
41    wc.lpfnWndProc     = (WNDPROC)WndProc;
42    wc.hInstance       = hInstance;
43    wc.hCursor         = LoadCursor(NULL, IDC_ARROW);
44    wc.hbrBackground   = (HBRUSH)(COLOR_BACKGROUND);
45    wc.lpszClassName   = (LPCTSTR)"TimerDemoClass";
46    RegisterClass(&wc);
47 
48     hWnd = CreateWindow("TimerDemoClass", "SetTimer/KillTimer Demo",WS_OVERLAPPEDWINDOW,
49        CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
50 
51    ShowWindow(hWnd, nCmdShow);
52    UpdateWindow(hWnd);
53    while (GetMessage(&msg, NULL, 0, 0)) 
54    {
55      DispatchMessage(&msg);
56    }
57    return 0;
58  }
59 
60  LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
61  {
62    time_t rawtime;
63    struct tm * timeinfo;
64    char buffer [80];
65    switch (message) 
66    {
67  #ifndef USE_TIMER_PROC
68      case WM_TIMER:
69        if(wParam == MY_TIMERID1) {
70          time (&rawtime);
71          timeinfo = localtime (&rawtime);
72          strftime (buffer,80,"Now time is %I:%M:%S%p.",timeinfo);
73          SetWindowText(hWnd, buffer);
74        }
75        break;
76      case WM_LBUTTONDOWN:
77        SetTimer(hWnd, MY_TIMERID1, 1000, NULL);
78        break;
79      case WM_RBUTTONDOWN:
80        KillTimer(hWnd, MY_TIMERID1);
81        break;
82  #else
83      case WM_LBUTTONDOWN:
84        SetTimer(hWnd, MY_TIMERID2, 1000, MyTimerProc);
85        break;
86      case WM_RBUTTONDOWN:
87        KillTimer(hWnd, MY_TIMERID2);
88        break;
89  #endif
90      case WM_DESTROY:
91        PostQuitMessage(0);
92        break;
93      default:
94        return DefWindowProc(hWnd, message, wParam, lParam);
95     }
96     return 0;
97  }

Output

SetTimer/KillTimer example demo application

You have viewed 1 page out of 109. Your VC++ learning is 0.00% complete. Login to check your learning progress.

 Vote 0

Similar topics related to this section

#Programming Windows, Fifth Edition (Developer Reference)
#Programming Applications for Microsoft Windows (Microsoft Programming Series)
#Programming Windows with MFC, Second Edition
#Visual C++ Programming
#Programming Microsoft Visual C++, Fifth Edition

* #1 webmaster Mon 28 Apr/2014 02:51:55(GMT)  Like 0 Unlike 0

Dear Users,

We are pleased to inform you that a forum/blog has been incorporated with www.mybestnotes.co.in. You are welcomed to add your comments, requests, codes, solutions and feedback to it. Please login(if already a member) or signup(for free) to avail to this facility.

Regards,
Webmaster

Your message goes here:

Name:Guest
Email:anonymous@unknown.com
My Post:*
Secutiry Code: ******  *
Preview this compose before posting this in discussion forum.
 
Note:
  1. Use [Sxx] code to show smiles. Example [S02]
  2. Use [URL ], example [URL http://www.google.com/]
  3. To display code or un formatted text use [CODE] [/CODE]. Example: [CODE] printf("Hello world"); [/CODE]
 [S01]   [S02]   [S03]   [S04]   [S05]   [S06]   [S07]   [S08] 
 [S09]   [S10]   [S11]   [S12]   [S13]   [S14]   [S15]   [S16] 
 [S17]   [S18]   [S19]   [S20]   [S21]   [S22]   [S23]   [S24] 

Note: Only members are allowed, * fields are mandatory.