如何使用 SetTimer API [英] How to use SetTimer API

查看:21
本文介绍了如何使用 SetTimer API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried to use SetTimer API to call a function every X minutes. So, i have written this test code

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

我应该每分钟都写一个 Hello 但它不起作用.

I should have Hello written every minute but it does not work.

推荐答案

你的程序有几个问题:

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

  1. C programs do end when they leave main() so there is no time when the timer can occur.
  2. Win32 timers need the message pump (see below) to be working, as they are implemented through WM_TIMER message, even when they are not associated with any window, and if you provide function callback.

当你指定一个 TimerProc 回调函数时,默认窗口过程在处理 WM_TIMER 时调用回调函数.因此,您需要在调用线程中调度消息,即使当您使用 TimerProc 而不是处理 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.

来源:MSDN:SetTimer 函数

  • 回调函数原型错误.请参阅 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来做到这一点).

    (Note this example program never ends, instead, real program should have some additional logic to do so by sending WM_QUIT).

    这篇关于如何使用 SetTimer API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆