Ian Young
Ian Young

Reputation: 1746

Utilize timer to update MFC Document/View application

I'm experimenting with a basic (template) MFC application, and I am looking to update the CDocument (representing the model) instance according to a timer event, for example, move a circle from one point in the client area to another point, according to elapsed time and velocity of the circle.

I've added the code to start the timer in the application class:

m_timer = m_pMainWnd->SetTimer( 16, 1000, NULL);

Which should send a timer message 60 times per second. However, I'm encountering several issues:

Adding a ON_WM_TIMER() entry to the message map for the derived CDocument .cpp file does not work, citing a c2446 error (casting a member function pointer to void pointer).

Trying the same with the concrete CView class does not cause an error, but the OnTimer function is never invoked.

The only place where OnTimer is ever invoked is in the derived CFrameWndEx class, using the following signature:

afx_msg void OnTimer( UINT_PTR nIDEvent );

As far as I can tell, there is no way for the CFrameWndEx to invoke changes in either the CView or CDocument derived classes.

I'm pretty sure this is simply down to my seriously lacking knowledge of MFC architecture, so I would appreciate some pointers.

Upvotes: 0

Views: 1316

Answers (2)

Sebastian Stern
Sebastian Stern

Reputation: 642

Like Joe Willcoxson suggested, simply put the OnTimer method within your concrete CView. However you then can't use the SetTimer method like you posted:

m_timer = m_pMainWnd->SetTimer( 16, 1000, NULL);

You have to call it somehere in your CView class, without m_pMainWnd, e.g. like:

CMyView::OnInitialUpdate()
{
    m_timer = SetTimer( 16, 1000, NULL); // also nullptr instead of NULL would be nice
}

Otherwise the main window will always be the CWnd that handles the message.

Upvotes: 1

Joseph Willcoxson
Joseph Willcoxson

Reputation: 6050

Add an OnTimer function and and ON_WM_TIMER message macro to your CView derived class. From the CView, you can call GetDocument(). That's the easiest way. Documents are not windows so they cannot handle window messages. The only thing they can handle is WM_COMMAND messages because of the way MFC gives the document a chance to respond to those messages via its command message routing.

Another way is to create a TIMERPROC function.

I recommend the first way.

Upvotes: 3

Related Questions