C++ 如何在基于 MFC 对话框的应用程序中使用计时器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7157079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:32:32  来源:igfitidea点击:

How to Use Timer in MFC Dialog based Application?

c++cmfc

提问by Ali Ahmed

I am developing MFC Dialog based application in Visual Studio 2008. I want to use timer that start on start of the application and continue to run and calls a function that performs my task? How can I do this?

我正在 Visual Studio 2008 中开发基于 MFC Dialog 的应用程序。我想使用在应用程序启动时启动的计时器并继续运行并调用执行我的任务的函数?我怎样才能做到这一点?

Thanks

谢谢

回答by Ajay

Just use SetTimermethod, and pass two arguments: Timer ID (any number), and the timeout in milliseconds. Then write up OnTimerimplementation, and an entry ON_WM_TIMERinside BEGIN_MESSAGE_MAP...END_MESSAGE_MAP.

只需使用SetTimer方法,并传递两个参数:计时器 ID(任意数字)和以毫秒为单位的超时时间。然后写出OnTimer实现,并在ON_WM_TIMER里面写一个条目BEGIN_MESSAGE_MAP...END_MESSAGE_MAP

CWnd::SetTimertakes 3 parameters, but only 2 are required. Pass third argument as NULL.

CWnd::SetTimer需要 3 个参数,但只需要 2 个。将第三个参数作为 NULL 传递。

CWnd::OnTimer

CWnd::OnTimer

回答by karx11erx

_AFXWIN_INLINE UINT_PTR CWnd::SetTimer(UINT_PTR nIDEvent, UINT nElapse,
    void (CALLBACK* lpfnTimer)(HWND, UINT, UINT_PTR, DWORD))

You may want to do something like

你可能想做类似的事情

UINT_PTR myTimer = SetTimer (1, 1000, null); // one event every 1000 ms = 1 s

and react to the ON_TIMER event in your window's event handler:

并对窗口事件处理程序中的 ON_TIMER 事件做出反应:

void CMyView::OnTimer (UINT_PTR nIdEvent)
{
if (nIdEvent == 1)
    // handle timer event
}

Alternatively you can pass a pointer to a function handling the timer events. Keeping the handle to the timer allows you to turn it off using KillTimer() in case you have to.

或者,您可以将指针传递给处理计时器事件的函数。保持计时器的句柄允许您在必要时使用 KillTimer() 将其关闭。

回答by Neophile

If you want to get the basic idea of using Timers, kindly have a look at this link and go through the step by step procedure on working with timers. After this, you should be able to use timers easily in your application whenever you want.

如果您想了解使用计时器的基本概念,请查看此链接并逐步了解使用计时器的步骤。在此之后,您应该能够随时在您的应用程序中轻松使用计时器。

Link: http://www.functionx.com/visualc/controls/timer.htm

链接:http: //www.functionx.com/visualc/controls/timer.htm

Hope this helps.

希望这可以帮助。

Cheers.

干杯。