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

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

问题描述

我试图每隔X分钟使用SetTimer API调用一个函数.所以,我已经编写了此测试代码

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天全站免登陆