Wednesday, September 16, 2009

Asynchronous Events Using Timers

Recently I was had an issue with Timer Call back function not working on Windows. I registered a simple call back function after 1 second, and it wasn't getting called, I was wondering how can it happen like that.

Then I did some study and found that, the windows will only send messages to your application that the timer is expired, and that message contains all the details such as the registered call back function etc, its the duty of the application to process these events and the call the windows API, DispatchMessage() which does the job of calling the call back function.

Here is the sample code, which works this way,
#include <windows.h>
#include <stdio.h>

int flag = 1;

void CALLBACK TimerProc(HWND, UINT, UINT, DWORD);

int main()
{
UINT_PTR id;
MSG msg;

id = SetTimer(NULL,
0,
3000,
(TIMERPROC) TimerProc);

while(flag)
{
GetMessage(&msg, NULL, 0, 0);
DispatchMessage(&msg);
}

KillTimer(NULL, id);

return 0;
}

void CALLBACK TimerProc(HWND hwnd,
UINT uMsg,
UINT idEvent,
DWORD dwTime)
{
flag = 0;
printf("I am in Timer Call Back Function \n");
}
So, if You are having the same problem as mine, please do follow this, and hope your problem is resolved, and do get back to me if you need any assistance.

The reason I think windows has been designed like this, is to make sure the call is made from the application context, hope that make sense, and I could not think of any other reason for doing it this way.

1 comment: