Click here to Skip to main content
15,880,608 members
Articles / Programming Languages / C++

Universal Progress Dialog

Rate me:
Please Sign up or sign in to vote.
3.67/5 (25 votes)
11 Mar 2011CPOL10 min read 229.3K   3.3K   109   64
A progress dialog that could be used anywhere, any time, for any task.

Introduction

In any interactive application, Progress-Dialogs (modal dialog boxes that display the progress of lengthy operations) play an important role in keeping the interface alive by providing the user real-time feedback about the application status. There is almost no context where these dialogs could not be used; ranging from simple file loading operations to complex OS loading operations, we find them useful. However, for each application that we develop, creating a new progress dialog from scratch is a boring task. Under these circumstances, we would find it useful to have a simple dialog template that could be used in any application, any time, for any task. Our Universal Progress Dialog that we are about to unleash here is one such modal dialog box that satisfies all these requirements, that is - it could be used any where, any time, for any operation.

The Universal Progress Dialog

The design goals that have driven the development of this Universal Progress Dialog are:

Simplicity (Usage should be as simple as possible)

In fact, as you would learn soon, you need to add just two extra lines to your existing code to start using this dialog in your app!!

Flexibility (Should be able to use it for any task)

This dialog is perfectly suitable to display the progress of any kind of operation that you know how to measure the progress. This is facilitated by accepting a pointer to any user defined function.

Interactivity (End-user should not suffer from loss of interactivity)

This dialog allows the end-user to cancel the operation anytime before the operation completes on its own. To facilitate this, the dialog internally manipulates a worker thread and manages the communication between the interface thread and the worker thread in a transparent way, freeing the developer from unnecessary thread-management issues.

With these design goals in mind, the class CUPDialog (no, it is not a CUP dialog - it is to mean CU that we are about to study provides a simple to use, flexible, and interactive interface in an elegant way very much similar to the well known CDialog class from MFC. All that we need to do is create the dialog class object and call the method DoModal() on it, as shown below:niversalProgressDialog)

C++
CUPDialog Dlg(...);         //construct the dialog class object

INT_PTR nResult = Dlg.DoModal();

if(nResult != IDOK) return;

The method CUPDialog::DoModal() displays a modal dialog box that returns IDOK upon successful completion. The dialog template that gets displayed is but a simple dialog box containing one progress bar, one static control, and one cancel button, as shown in Figure 1. As could be expected easily, the progress bar displays the progress of the underlying lengthy operation while the static control displays any suitable text appropriate for the operation. The Cancel button allows the user to cancel the operation at any time before the operation gets completed on its own.

Dialog Template For the Universal Progress Dialog

Figure 1: Dialog template for the Universal Progress Dialog

When CUPDialog::DoModal() is invoked, the dialog box automatically creates a background worker thread and schedules a user supplied function for execution in that thread's context. We can specify which function should be executed by supplying a pointer to the function as one of the parameters of the CUPDialog class constructor. The complete prototype of the constructor of CUPDialog is:

C++
CUPDialog(HWND hParentWnd,LP_CUPDIALOG_USERPROC lpUserProc, 
  LPVOID lpUserProcParam,LPCTSTR lpszDlgTitle=_T("Please Wait.."), 
  bool bAllowCancel=true);

The parameters for the constructor are:

HWND hParentWnd

The application window that is creating the dialog box. This value would be used as the parent window handle for the dialog box.

LP_CUPDIALOG_USERPROC lpUserProc

Pointer to a user defined function. The dialog box internally creates a thread and executes this function in that thread's context. The function should be of the form:

C++
bool UserProc(const CUPDUPDATA* pParam);
LPVOID lpUserProcParam

Argument for the user defined function. This value could be accessed from the UserProc by accessing the method CUPDUPDATA::GetAppData().

LPCTSTR lpszDlgTitle

Parameter specifying the caption for the progress dialog. Default value = _T("Please Wait..").

bool bAllowCancel

Parameter indicating if the user can cancel the operation. When set to false, the Cancel button would be disabled so that the user cannot cancel the operation. The default value is true.

For example, the following code fragment executes a function LengthyOperationProc() while displaying a cancelable modal dialog box with the default title "Please Wait..".

C++
bool LengthyOperationProc(const CUPDUPDATA* pCUPDUPData);

void CApplicationDlg::OnBnClickedOk()
{
    int nData =0;
    
    CUPDialog Dlg(GetSafeHwnd(),LengthyOperationProc,&nData);
    
    INT_PTR nResult = Dlg.DoModal();    
}

In the above code, we are trying to display the progress dialog for some lengthy operation to be executed in the function LengtyOperationProc(). As per the prototype requirements, the function LengtyOperationProc() accepts a CUPDUPDATA* as an argument and returns a boolean value as a result. CUPDUPDATA is meant for CUniversalProgressDialogUserProcedureDATA. This key structure supports the following important methods:

LPVOID GetAppData()

Provides access to the user supplied parameter. This value is the same as the third parameter supplied as part of the CUPDialog constructor.

bool ShouldTerminate()

Indicates if the function should terminate. We should execute our lengthy operation only if this return value is false. This would return true when the user has cancelled the dialog - which means we should stop and return. We should check this frequently so as not to stall the app.

void SetProgress(LPCTSTR lpszText)

This facilitates us to set the text for the static control appropriately as per the progress.

void SetProgress(UINT_PTR dwPbarPos)

This facilitates us to set the position for the progress bar control appropriately as per the progress.

void SetProgress(LPCTSTR lpszText,UINT_PTR dwPbarPos)

This facilitates us to set both the text of the static control and the position of the progress control at the same time as per the progress appropriately.

void AllowCancel(bool bAllow)

Useful for enabling or disabling the Cancel button on the progress dialog.

void SetDialogCaption(LPCTSTR lpszDialogCaption)

Facilitates modifying the progress dialog caption.

To demonstrate the use of CUPDUPDATA, let's consider some pseudo lengthy operation: counting numbers from 1 to 100. As part of this operation, we wish to display the progress for each number that we counted. The code fragment that achieves such a thing would look like the following:

C++
bool LengthyOperationProc (const CUPDUPDATA* pCUPDUPData)
{
    int* pnCount= (int*)pCUPDUPData->GetAppData();    
    //Retrieve the App Supplied Data
    
    pCUPDUPData->SetProgress(_T("Counting.."),0);
    
    while(pCUPDUPData->ShouldTerminate()== false && *pnCount != 100)
    {
        pCUPDUPData->SetProgress(*pnCount); //Update Progress Bar
                         
        *pnCount = *pnCount + 1;
    
        Sleep(100);
    }
    
    pCUPDUPData->SetProgress(_T("Done !!"),100);
    
    return true;
}

In the above, we are first retrieving a pointer to the user supplied number by using the method GetAppData(). Then we start by setting the progress bar to 0, and for each number that is counted, we are repositioning the progress bar to reflect the latest status. Please observe the usage of CUPDUPData::ShouldTerminate() in the main while loop. The method ShouldTerminate() returns true only when the user presses the Cancel button or the close system button. By placing the ShouldTerminate() check in the loop, we are making sure that we would stop immediately as and when the user wants. It is a good practice with this design to keep such a check as often as possible so that we could respond immediately the moment the user cancels the dialog. Its importance need not be stressed twice given the fact that we are executing the function in a background thread context and not in the main application thread context.

Finally, when done, we set the progress to 100 and exit from the function by returning true. This indicates that we have successfully completed the lengthy operation, which results in a return value of IDOK for the method CUPDialog::DoModal(). However, we may sometimes require indicating failure in the lengthy operation. For example, in operations that involve file manipulations, we may encounter file loading/reading/writing errors. In such cases, we exit from the function by returning false. This would result in a return value of INT_PTR made of LOWORD(IDCANCEL) and HIWORD(0) for the method CUPDialog::DoModal(). In case of the user canceling the dialog before the operation gets completed on its own, the return value for the method CUPDialog::DoModal() would be an INT_PTR made of LOWORD(IDCANCEL) and HIWORD(1). The following code fragment illustrates such an error checking mechanism:

C++
bool LengthyOperationProc(const CUPDUPDATA* pCUPDUPData);

void CApplicationDlg::OnBnClickedOk()
{
    CUPDialog Dlg(GetSafeHwnd(), LengthyOperationProc, this);
    
    INT_PTR nResult = Dlg.DoModal();
    
    if(nResult != IDOK)
    {
        if(!HIWORD(nResult))
            MessageBox(_T("Error Occurred !!"));
        else
            MessageBox(_T("User Cancelled the Dialog !!"));
    }
}

In any typical application, when the user presses the Cancel button before the operation gets completed on its own, the value related to CUPDUPData::ShouldTerminate() would be set to true by the dialog. However, if we are unable to check it immediately due to any reason such as being stuck in some time consuming primitive operations or forgetting to call CUPDUPData::ShouldTerminate(), the dialog would wait for some time before actually returning the control to the parent window. In such a case, the thread might still continue to execute in the background even though the dialog box has terminated. It would be killed when the dialog class object variable gets out of scope. That is, the thread would get killed in the destructor of the CUPDialog object, if still found alive by that time.

What you should do

To use this Universal Progress Dialog in your code, all that you need to do is add the UPDialog.h, UPDialog.cpp, and InitCommonControls.h files from the demo application into your project, and start using the CUPDialog class. The UPDialog.h file contains the CUPDialog class declaration and other related structures, and can be accessed from your code with:

C++
#include "UPDialog.h"

Wherever you require to display the progress operation, declare a variable for the class CUPDialog and call the method CUPDialog::DoModal() on it. (Do not worry about creating a dialog resource. CUPDialog has a built-in template that it can load from memory.) To declare the variable for the class CUPDialog, you need to pass the function you want to execute in the background as a constructor parameter. Remember that the function should be of the form:

C++
bool UserProc(const CUPDUPDATA* pParam);

In the function body, use the overloaded methods CUPDUPDATA::SetProgress() and CUPDUPDATA::ShouldTerminate() to set the progress, and to determine if the user has cancelled the dialog, respectively. To access the data that you have supplied, use the CUPDUPDATA::GetAppData() method.

Please note that this function is being executed in a different thread context than the main application thread context. So, your application remains being interactive while performing your lengthy operation. Feel free to use it any where, for any operation, any number of times!!

What you could do

In case you have already designed some dialog template of your own containing more controls, or have a similar dialog but with different control ID values, you can still benefit from this CUPDialog.

All that you need to do is use the method CUPDialog::SetDialogTemplate() passing your own custom dialog template resource name and the static progress bar and cancel button control IDs.

C++
inline void SetDialogTemplate(HINSTANCE hInst, LPCTSTR lpTemplateName, 
       int StaticControlId, int ProgressBarControlId, int CancelButtonId)

CUPDialog::SetDialogTemplate() accepts the control IDs at runtime instead of choosing them at compile time. This way, CUPDialog can provide the runtime logic for more than one template simultaneously. The first parameter to this method is a HINSTANCE of the dialog resource, which makes it possible for you to supply a template that can be loaded from other modules.

To process any additional control messages for your custom dialog box, you can use the overloaded CUPDialog::OnMessage() method.

C++
INT_PTR OnMessage(HWND hDlg,UINT Message,WPARAM wParam,LPARAM lParam, BOOL bProcessed)

This CUPDialog::OnMessage() gets called whenever the dialog receives a message (from WM_INTIDIALOG onwards). You can override this method in a CUPDialog derived class of your own and process the additional messages. Please refer to the sample demo application to see this in action.

Furthermore, to refine the time the dialog should wait after signaling the termination, you can use the method CUPDialog::SetTerminationDelay().

C++
#define CUPDIALOG_TERMINATE_DELAY    (500)    //Time to wait in MilliSeconds

By default, the dialog waits for 500ms. Changing it to larger values (such as 1000) would make the dialog wait for more time (1000ms), and to smaller values would make it wait for less time. Both are not suggestible actions as they would either cause the dialog to stall for long times or the thread to get killed prematurely. The default value of 500ms is suitable for most applications. Note that this value is used only for forced terminations, such as the user canceling the dialog, and that too if the thread is found to be alive at the time of cancellation. If the thread completes on its own before any interruption, then this value would not come into scene. This way, both efficiency and interactivity are guaranteed to be at their best in all situations.

Conclusions

The Universal Progress Dialog is a simple modal dialog box aimed to be handy in most cases where we want to add a simple progress dialog without wasting much time redesigning a template and logic from scratch. You could use it any where, any time, for any task. The next time you feel an operation is taking a long time, try and see if you could plug in this CUPDialog. All it needs is adding two more lines of code.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
Creator of CarMusTy - Carnatic Music Typesetting Application, and the CFugue C++ Runtime Environment for MusicNote Programming.

Comments and Discussions

 
QuestionIs there a way to make the progress control style marquee? Pin
Sharon Gottlieb8-Nov-15 23:56
Sharon Gottlieb8-Nov-15 23:56 
AnswerRe: Is there a way to make the progress control style marquee? Pin
Sharon Gottlieb15-Nov-15 22:20
Sharon Gottlieb15-Nov-15 22:20 
Questionthanks it's really good Pin
hohogpb26-Aug-14 22:44
hohogpb26-Aug-14 22:44 
GeneralMy vote of 1 Pin
John.SMITH_197715-Mar-11 11:02
John.SMITH_197715-Mar-11 11:02 
GeneralMy 5 Pin
Sharjith14-Mar-11 16:08
professionalSharjith14-Mar-11 16:08 
GeneralAfxGetThread return NULL on the thread updialog created(vs2008) Pin
bsd91210-Mar-11 15:45
bsd91210-Mar-11 15:45 
GeneralRe: AfxGetThread return NULL on the thread updialog created(vs2008) Pin
Gopalakrishna Palem10-Mar-11 17:00
Gopalakrishna Palem10-Mar-11 17:00 
GeneralRe: AfxGetThread return NULL on the thread updialog created(vs2008) Pin
bsd91211-Mar-11 3:42
bsd91211-Mar-11 3:42 
GeneralMy vote of 5 Pin
LamerExterminator12-Jul-10 14:50
LamerExterminator12-Jul-10 14:50 
GeneralWorks for me. Now.... Pin
LamerExterminator12-Jul-10 14:48
LamerExterminator12-Jul-10 14:48 
GeneralRe: Works for me. Now.... Pin
Gopalakrishna Palem12-Jul-10 16:48
Gopalakrishna Palem12-Jul-10 16:48 
GeneralRe: Works for me. Now.... Pin
LamerExterminator12-Jul-10 17:52
LamerExterminator12-Jul-10 17:52 
GeneralUpdated Code Pin
TXAggie009-Jul-10 8:29
TXAggie009-Jul-10 8:29 
GeneralRe: Updated Code Pin
TXAggie009-Jul-10 8:31
TXAggie009-Jul-10 8:31 
GeneralRe: Updated Code Pin
Gopalakrishna Palem9-Jul-10 15:19
Gopalakrishna Palem9-Jul-10 15:19 
GeneralOpenGL and Threads Pin
OllieBrown10-Mar-10 10:50
OllieBrown10-Mar-10 10:50 
GeneralRe: OpenGL and Threads Pin
Gopalakrishna Palem12-Mar-10 14:40
Gopalakrishna Palem12-Mar-10 14:40 
GeneralThread Termination Pin
barto8-Apr-09 1:58
barto8-Apr-09 1:58 
GeneralRe: Thread Termination Pin
Gopalakrishna Palem8-Apr-09 3:55
Gopalakrishna Palem8-Apr-09 3:55 
GeneralExcellent job - 2 questions Pin
wartin10-Mar-09 4:15
wartin10-Mar-09 4:15 
GeneralUpdated code without requiring resource Pin
Gopalakrishna Palem11-Mar-09 3:09
Gopalakrishna Palem11-Mar-09 3:09 
QuestionDoes not run in object-oriented code? Pin
Luke DeStevens16-Oct-07 3:34
Luke DeStevens16-Oct-07 3:34 
Hello,

After some bit of work, I finally got your code to compile in an ATL environment. Oddly enough, it seems that none of your code makes any AFX (MFC) calls.

Anyway, I am trying to use your progress window in an object that is a member object of a plugin for another program. In order to get it to compile, I had to set the LengthyOperation as a static function. In fact, I had to define LengthyOperation as a static function that tracks a member variable (though address passing) as another method (which is passed a tree node) performs the process (since the lengthy operation requires recursion through a tree). Basically, all leaves are counted, then as each leaf is saved, a tracker struct is updated. LengthyProcess (called TrackProgress) continues to look at this struct (through the address passed at the window creation) to update the status bar.

Unfortunately, it doesn't work. It compiles, but I never see the status bar. In fact, TrackProgress never gets initiated, or at least the Message Boxes I put in there don't come up, either. I think this may be due to using a static function. Either that, or I've screwed up Threading in ATL but the compiler doesn't catch how.

So, I guess what I'm asking is this: how can I modify your CUPDialog in order for it to accept pointers to non-static member functions? Also, do you know of any quirks in trying to run this window in ATL?

Thanks in advance.

Luke
AnswerRe: Does not run in object-oriented code? Pin
Luke DeStevens21-Oct-07 7:20
Luke DeStevens21-Oct-07 7:20 
GeneralRe: Does not run in object-oriented code? Pin
Luke DeStevens22-Oct-07 9:43
Luke DeStevens22-Oct-07 9:43 
GeneralRe: Does not run in object-oriented code? Pin
Gopalakrishna Palem24-Oct-07 4:23
Gopalakrishna Palem24-Oct-07 4:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.