我尝试使用 SetTimer
API 每隔 X 分钟调用一个函数。所以,我写了这段测试代码
void f()
{
printf("Hello");
}
int main()
{
SetTimer(NULL, 0, 1000*60,(TIMERPROC) &f);
}
我应该每分钟都写下你好,但它不起作用。
最佳答案
你的程序有几个问题:
- C 程序在离开
main()
时确实会结束,因此没有时间可以触发计时器。 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
回调函数的原型(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/