It should be emphasised that, as in bithub's sample, SetTimer requires a message loop to be run on the same thread. For a DLL, this means either that you start a new thread that calls SetTimer and runs a message loop, or you have a requirement that the calling thread runs a message loop.
There are some other alternatives. Timer queues were introduced with Windows 2000. These use a thread from the thread-pool to run the callback and are fairly simple to set up:
Code:
#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <stdio.h>
/* Functions in your dll. */
HANDLE g_hTimer;
VOID CALLBACK TimerCallback(PVOID lpParameter, BOOLEAN reserved)
{
/* Remember this callback is executed in a different thread,
* so use synchronization if needed. */
printf("Timer called\n");
}
void Start(void)
{
PVOID param = NULL; /* You can use this to pass a value to the callback. */
DWORD interval = 100; /* Interval in milliseconds. */
CreateTimerQueueTimer(&g_hTimer, NULL, TimerCallback, param, interval, interval, 0);
}
void End(void)
{
DeleteTimerQueueTimer(NULL, g_hTimer, INVALID_HANDLE_VALUE);
}
/* Calling function. */
int main(void)
{
Start();
getchar();
End();
getchar();
return 0;
}
Another option is CreateWaitableTimer. You would have to start a new thread and wait on your created timer in a loop. It has the advantage over timer queues that it is available on earlier platforms.