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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章