Download demo project - 16 Kb
<!-- Article Starts -->
This article shows how to update the contents of the modal dialog using
a callback functions.
Some background first. When developing communication applications, it
is usually necessary to display a modal dialog box that contains some information
about what is happening in the background (statistics, state of the communication
etc). Most common solution is to pass all the knowledge about the background
process(es) to the modal dialog and then use a timer to periodically update
the contents of the dialog controls. This solution is Ok but complicates
the design of the dialog and makes it very difficult to have a generic
dialog that displays different kind of information depending on the place
where it is created. Important side-effect of this solution is either the
need to provide access to all data members of the background process classes
to the dialog or the need to declare all data members public. Both options
complicate the source code.
The solution presented here uses a callback function given to the dialog
via its constructor. Callback function is a member function that belongs
to a CWnd derived class (exactly the same technique may be used with a
callback function belonging to the CObject derived class). The responsibility
of the dialog is to create a timer and periodically (from within OnTimer()
handler) call the supplied callback function. Dialog may give some information
to the callback function. It will collect dta from the callback function
and use it to update the contents of its controls. Contrary to the common
solution presented above, only the callback function needs to have access
to background process and since it is a callback function it may as well
be a part of the background process.
This design reduces the complexity of the dialog and enables a generic
dialog to display different kind of information using different types of
callback functions. Another important side-effect is that the application
design is simpler and more robust.
First, we need to create a callback function type:
typedef BOOL (CWnd::*TWindowUpdate)(int& nCount, CString& sText, DWORD dwData);
Arguments of this function are application specific. Then we modify the
constructor of the dialog:
TTestDialog(TWindowUpdate pUpdateCallback, CWnd *pWindow,
DWORD dwData = 0, CWnd* pParent = NULL)
At last, we call the callback function (most often from the OnTimer() handler).
if (m_pWindow && m_pWindowUpdateCallback)
int nCount = 0;
if ((m_pWindow->*m_pWindowUpdateCallback)(nCount, str, m_dwData))
Callback function is implemented in a CWnd derived window (main frame, view etc).