Задача: Таймер
Исходник: Таймер для неоконных классов, язык: C++ [code #603, hits: 10673]
автор: - [добавлен: 23.12.2009]
  1. #include<windows.h>
  2. #include<map>
  3.  
  4. class callback_t {
  5. public:
  6. virtual void invoke() = 0;
  7. };
  8.  
  9. template<class T>
  10. class callback0 : public callback_t {
  11. typedef void (T::*func_t)();
  12. T* cls_;
  13. func_t func_;
  14. public:
  15. void attach(T* cls, func_t func)
  16. { cls_ = cls; func_ = func; }
  17. void invoke()
  18. { (cls_->*func_)(); }
  19. };
  20.  
  21. template<class T, typename P1>
  22. class callback1 : public callback_t {
  23. typedef void (T::*func_t)(P1);
  24. T* cls_;
  25. func_t func_;
  26. P1 p1_;
  27. public:
  28. void attach(T* cls, func_t func, P1 p1)
  29. { cls_ = cls; func_ = func; p1_ = p1; }
  30. void invoke()
  31. { (cls_->*func_)(p1_); }
  32. };
  33.  
  34. typedef std::map<UINT_PTR, callback_t*> timer_map_t;
  35.  
  36. static timer_map_t g_timer_map;
  37.  
  38. static void CALLBACK TimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
  39. {
  40. timer_map_t::const_iterator it = g_timer_map.find(idEvent);
  41. if (it == g_timer_map.end()) return;
  42.  
  43. callback_t* cb = it->second;
  44. if (cb == NULL) return;
  45.  
  46. cb->invoke();
  47. }
  48.  
  49. UINT_PTR ex_set_timer(UINT_PTR id, unsigned int period, callback_t* cb)
  50. {
  51. UINT_PTR new_id = SetTimer(NULL, id, period, TimerProc);
  52. g_timer_map[new_id] = cb;
  53.  
  54. return new_id;
  55. }
  56.  
  57. bool ex_kill_timer(UINT_PTR idEvent)
  58. {
  59. timer_map_t::const_iterator it = g_timer_map.find(idEvent);
  60. if (it == g_timer_map.end()) return false;
  61.  
  62. g_timer_map.erase(it);
  63.  
  64. return true;
  65. }
  66.  
  67. //
  68. // пример
  69. //
  70.  
  71. class MyClass {
  72. callback1<MyClass, int> cb_;
  73. UINT_PTR timer_;
  74. public:
  75. void init() {
  76. cb_.attach(this, &MyClass::on_timer, 10);
  77. timer_ = ex_set_timer(0, 0, &cb_);
  78. }
  79. void destroy() {
  80. ex_kill_timer( timer_ );
  81. }
  82. void on_timer(int tag) {};
  83. };
  84.  
  85. void main()
  86. {
  87. MyClass obj1;
  88.  
  89. obj1.init();
  90.  
  91. //MessagePump();
  92. }
менеджер таймеров, с вызовом методов класса

источник rsdn.ru

+добавить реализацию