c++ - 如何使用 SetTimer API

标签 c++ windows api

我尝试使用 SetTimer API 每隔 X 分钟调用一个函数。所以,我写了这段测试代码

void f()
{
 printf("Hello");
}
int main() 
{
 SetTimer(NULL, 0, 1000*60,(TIMERPROC) &f); 
}

我应该每分钟都写下你好,但它不起作用。

最佳答案

你的程序有几个问题:

  1. C 程序在离开 main() 时确实会结束,因此没有时间可以触发计时器。
  2. Win32 计时器需要消息泵(见下文)才能工作,因为它们是通过 WM_TIMER 消息实现的,即使它们没有与任何窗口相关联,并且如果您提供函数回调。

    When you specify a TimerProc callback function, the default window procedure calls the callback function when it processes WM_TIMER. Therefore, you need to dispatch messages in the calling thread, even when you use TimerProc instead of processing WM_TIMER.

    Source: MSDN: SetTimer function

  3. 回调函数的原型(prototype)错误。参见 http://msdn.microsoft.com/en-us/library/windows/desktop/ms644907%28v=vs.85%29.aspx

    void CALLBACK f(HWND hwnd, UINT uMsg, UINT timerId, DWORD dwTime)
    {
      printf("Hello");
    }
    
    int main() 
    {
      MSG msg;
    
      SetTimer(NULL, 0, 1000*60,(TIMERPROC) &f);
      while(GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
      }
    
      return 0;
    }
    

(注意这个示例程序永远不会结束,相反,真实的程序应该有一些额外的逻辑来发送 WM_QUIT)。

关于c++ - 如何使用 SetTimer API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15685095/

相关文章:

c++ - 为什么我可以在通过 'auto' 的基于范围的 for 循环中使用 'std::pair' 而不是 'std::unordered_map' 对非常量的引用?

c++ - 什么决定了 OpenGL ES 2.0 中屏幕网格的尺寸? (使用 C++)

python - Hyperledger Sawtooth 验证器——设备上没有空间

c++ - Linux 共享库链接错误( undefined symbol )

c++ - 链接时间优化与多线程支持冲突

c++ - 通过 C/C++ 连接到 Facebook 的最佳方式是什么?

javascript - 如何通过JSON在MySQL中插入Date类型变量

javascript - 使用 Javascript 模拟 API 调用

windows - 如何在 Windows 上静态编译 SDL 游戏

linux - 如何从批处理文件在putty上执行命令?