20070511

Windows中的计时器(SetTimer和CreateWaitableTimer)

Windows中的计时器(SetTimer和CreateWaitableTimer)   
Timers (SetTimer and CreateWaitableTimer) in Windows
       
1.SetTimer
下面的例子创建了一个计时器(不与窗口相关联),该计时器过程函数建了20个消息框。
The following example creates a timer (that is not attached to a window) whose Timer Procedure creates 20 Message Boxes

#include <windows.h>

class foo_class {
  static int counter;
public:
  //static函数,相当于全局
  static void  __stdcall timer_proc(HWND,unsigned int, unsigned int, unsigned long) {
    if (counter++ < 20)
      MessageBox(0,"Hello","MessageBox",0);
    else
      PostQuitMessage(0);
  }
};

int foo_class::counter=0;

WINAPI WinMain(HINSTANCE,HINSTANCE,LPSTR,int) {

//第1个参数,MSDN中指出如果置为NULL,即0,不与窗口相关联。
//If this parameter is NULL, no window is associated with the timer and the nIDEvent parameter is ignored.
//第2个参数会被忽略
//第3个参数,300毫秒触发一次
//第4个参数,触发时由函数foo_class::timer_proc响应
int iTimerID = SetTimer(0, 0, 300, foo_class::timer_proc);
  MSG m;
//这是消息循环
  while (GetMessage(&m,0,0,0)) {
    TranslateMessage(&m);
    DispatchMessage(&m);

   }
  return 1;
}

2.CreateWaitableTimer
这个例子演示如何在windows中使用计时器。
计时器被设计为(1)在第1次调用CreateWaitableTimer后2秒触发,(2)此后每3/4秒触发一次。
#define _WIN32_WINNT 0x0400

#include <windows.h>
#include <process.h>
#include <stdio.h>

unsigned __stdcall TF(void* arg) {
  HANDLE timer=(HANDLE) arg;

  while (1) {
    //此处,进程间通信的接收方
    //timer是命名的,因此进程间或线程间没有区别
    WaitForSingleObject(timer,INFINITE);
    printf(".");
  }

}

int main(int argc, char* argv[]) {
  //创建,命名为0,也可以是LPCTSTR,字符串
  //其他进程可以通过OpenWaitableTimer获得此timer的句柄,并对之进行SetWaitableTimer
  HANDLE timer = CreateWaitableTimer(
    0,
    false, // false=>will be automatically reset
    0);    // name

  LARGE_INTEGER li;

  const int unitsPerSecond=10*1000*1000; // 100 nano seconds

  // Set the event the first time 2 seconds
  // after calling SetWaitableTimer
  //2秒
  li.QuadPart=-(2*unitsPerSecond);
  //通过句柄设置timer
  SetWaitableTimer(
    timer,
    &li,
    750,   // Set the event every 750 milli Seconds
    0,
    0,
    false);
  //用TF函数启动worker线程
  _beginthreadex(0,0,TF,(void*) timer,0,0);

  // Wait forever,
  while (1) ;

  return 0;
}


参考:
1.[http://www.adp-gmbh.ch/win/misc/timer.html ]
2.[http://support.microsoft.com/kb/184796],中文的

No comments: