l3utterfly
l3utterfly

Reputation: 2186

MFC Timer One-time Execute

I'm programming in c++ using MFC.

I want to make a piece of code execute after the UI has fully loaded, so I put it in a OnTimer callback and called SetTimer in the OnInitDialog. The problem is how to make that timer only execute once?

Any help would be appreciated.

Upvotes: 0

Views: 2605

Answers (3)

edtheprogrammerguy
edtheprogrammerguy

Reputation: 6039

Instead of using a timer, you can also post yourself a message with PostMessage, which will let the pending window message queue get processed. Then you can do what you want in the PostMessage handler. That way you don't have to worry about killing a timer. (see http://msdn.microsoft.com/en-us/library/9tdesxec%28v=vs.80%29.aspx)

Upvotes: 1

hyun
hyun

Reputation: 2143

You have to use KillTimer function, but you need to be careful for only once executing timer. For example, you write code like below,

#define TID_ONLY_ONCE WM_USER + 202
void CSampleDlg::OnTimer(UINT_PTR nIDEvent)
{
    if(nIDEvent == TID_ONLY_ONCE)
    {
        KillTimer(TID_ONLY_ONCE);
        SomethingLongProcess(pSomeData);
    }
    CDialog::OnTimer(nIDEvent);
}

If you set timer elapse shortly, although you call KillTimer, 'ontimer()' will be executed several times, because SomethingLongProcess requires long times. So that, to avoid this,

  • Call KillTimer() immediately after calling SetTimer().
  • Or use global bool member. After calling SetTimer, global member set to true, and then in OnTimer(), check this value whether SomethingLongProcess() will be executed.

I hope this will help you a little.

Upvotes: 3

ScottMcP-MVP
ScottMcP-MVP

Reputation: 10425

The first time the timer function is called call KillTimer.

Upvotes: -1

Related Questions