The progress dialog

It's one of those boring tasks we all hate to do: writing a progress dialog. It ranks right up there with typing
"ListView_SetExtendedListViewStyleEx". And even if you're able to reuse an existing dialog, it might
not look just the way you want it to, or it might be tough to integrate into your code.

Fortunately, IE 5 saves us from having to build a dialog or write code to handle a Cancel button ever again!
The BROWSEUI.DLL file implements a COM interface called IProgressDialog that provides
a dialog that looks like the one displayed by Explorer and SHFileOperation().

The progress dialog has these features:

The AVI file should be 272x60 and is subject to the normal restrictions of the animation common control. If you
don't have an AVI of your own, MSVC comes with some sample ones (in the \common\graphics\avis directory on the CD), or you can open up shell32.dll in the
resource editor and swipe one from there. (If you were wondering, I snagged the AVI in the screen shot above from
Internet FastFind.)

Even though the documentation states that you can remove the minimize button from the dialog, this appears to
be broken, even in build 2195 of Windows 2000. The dialog will always have a minimize button (for the time
being, until Microsoft fixes it).

Since the COM methods have several flags and reserved parameters, I wrote a thin MFC wrapper class, CSHProgressWnd,
that makes your code much more readable. The MFC class is not derived from CWnd since the COM interface doesn't
provide access to the progress window directly. That means you can use the wrapper even in console apps or other
situations where you don't use the CWnd framework. I don't use much MFC stuff (the features I use most are memory
validation routines like AfxIsValidString()), so you can very easily remove the dependency on MFC
if you so desire.

If you're wondering about the name, I put the "SH" in the class name because MSDN states that the
IProgressDialog interface is actually part of shell32.dll (and only available on Windows 2000!), and
I used "SH" to indicate that it was a shell feature. I later discovered that the dialog works fine on
older versions of Windows, but by that time I'd finished the code.

CSHProgressWnd Functions

Construction/destruction

The CSHProgressWnd constructor creates an IProgressDialog object. On a properly-working
system, this will always succeed. However, you can call the IsValid() function if you want to double-check
that everything worked. Note that you must initialize OLE (such as with AfxOleInit()) before constructing
a CSHProgressWnd object.

The CSHProgressWnd destructor destroys the dialog and releases the COM interface.

Dialog setup

Call these functions to determine how the dialog will look.

void SetTitle ( LPCTSTR szTitle )Sets the text that appears in the caption bar of the progress dialog.

void SetAnimation ( HINSTANCE hinst, UINT uRsrcID )
void SetAnimation ( UINT uRsrcID )
Specifies a resource containing an AVI that will be shown in the dialog. The first function takes the HINSTANCE
of the module containing the resource. The second form uses the return from AfxGetResourceHandle()
as the module.

void SetCancelMessage ( LPCTSTR szMessage )Sets the text that is shown on line 3 when the user clicks the Cancel button.

void SetCalculateTime ( bool bCalculate = true )
Sets whether the progress dialog shows an estimate of the time remaining on line 3. If you don't call SetCalculateTime(),
the dialog defaults to showing the time remaining.

void SetAllowMinimize ( bool bAllow = true )
Sets whether the progress dialog includes a minimize button. If you don't call SetAllowMinimize(),
the dialog defaults to having a minimize button. NOTE: Calling SetAllowMinimize(false) will not
remove the minimize button; this appears to be a bug in the dialog implementation.

Showing the dialog

The progress dialog can be modal or modeless. Call one of these two functions to display the dialog.

HRESULT ShowModal ( CWnd* pwndParent )
Displays the dialog as a modal dialog. pwndParent is a pointer to the parent window. Test the return
value with the SUCCEEDED() macro to determine if the dialog was created successfully. If the dialog
is not created, the return value is the error returned by the IProgressDialog::StartProgressDialog()
method.

HRESULT ShowModeless ( CWnd* pwndParent )
Same as ShowModal(), but the progress dialog is modeless instead of modal.

Updating the progress

void SetLineText ( DWORD dwLine, LPCTSTR szText, bool bCompactPath = false )Sets one of the three lines of text in the dialog. dwLine can be 1, 2, or 3. Lines 1 and 2 appear
between the AVI and the progress bar, and line 3 appears under the progress bar. If you have the dialog calculate
the time remaining (by calling SetCalculateTime(true)), the dialog uses line 3 to display the estimated
time remaining, and that line is unavailable to SetLineText(). If you are displaying a file name or
path, pass true for the third parameter to have the dialog shorten the path so it fits in the dialog.

void UpdateProgress ( DWORD dwProgress, DWORD dwMax )
void UpdateProgress ( DWORD dwProgress )UpdateProgress() sets the dialog's progress indicator. The first form of the function sets the current
and maximum progress values. These may be, for example, 0 and 100, but the exact values are up to you. You must
call the first form the first time, then afterwards you can call the second form as long as your maximum progress
value does not change. You may freely change the maximum value if you need to, as long as you call the first form
whenever the maximum value changes.

Other functions

bool HasUserCanceled()You should call HasUserCanceled() periodically during your processing, and break out if the function
returns true.

void EndDialog()
Call EndDialog() to close the progress dialog. The CSHProgressWnd destructor will also
close the dialog if it is still visible.

void ResetTimer()
If you want to reset the timer used by the dialog to estimate the time remaining, call ResetTimer()
at the beginning of your processing loop. The dialog uses the time between calls to ResetTimer() and
UpdateProgress() to calculate the time remaining. Normally you won't need to call this function; if
you don't call it, the dialog will base its estimate on the time elapsed between creation of the dialog (via ShowModal()
or ShowModeless()) and the first call to UpdateProgress().

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

Share

About the Author

Michael lives in sunny Mountain View, California. He started programming with an Apple //e in 4th grade, graduated from UCLA with a math degree in 1994, and immediately landed a job as a QA engineer at Symantec, working on the Norton AntiVirus team. He pretty much taught himself Windows and MFC programming, and in 1999 he designed and coded a new interface for Norton AntiVirus 2000.
Mike has been a a developer at Napster and at his own lil' startup, Zabersoft, a development company he co-founded with offices in Los Angeles and Odense, Denmark. Mike is now a senior engineer at VMware.

He also enjoys his hobbies of playing pinball, bike riding, photography, and Domion on Friday nights (current favorite combo: Village + double Pirate Ship). He would get his own snooker table too if they weren't so darn big! He is also sad that he's forgotten the languages he's studied: French, Mandarin Chinese, and Japanese.

The IProgressDialog object has a well-known bug with PROGDLG_MODAL. If progress dialog's parent window is the application's main window, your application can lose activation when the progress dialog closes.

The result is that your application disappears behind the windows of other applications.

The obvious workaround is ::SetForegroundWindow(hWndParent). But testing on XP and W2K3 SP1 shows that it does not work. Or at best works erratically.

I did some research and figured out why the bug is happening. StartProgressDialog creates a new thread to host the progress window. When the window receives WM_DESTROY message it ought to re-enable the parent window. But it doesn't. (This the bug.) Instead, StopProgressDialog() wrongly attempts to re-enable the parent in the calling thread (our thread), after the progress window is destroyed and the progress thread has died.

When the progress window dies, the system tries to assign a new foreground window. It cannot assign to hwndParent because StartProgressDialog (w/PROGDLG_MODAL) disabled the parent window.

So the system hands the foreground activation to the next process that wants it in the system foreground queue. Thus we lose our right to recapture the foreground window. I'm assuming SPI_SETFOREGROUNDLOCKTIMEOUT is non-zero, which is true by default on XP and W2K3.

What makes things really interesting is that if you happen to attach a debugger to the process (for example to try to figure out this crazy bug), USER32 changes its behavior! When a debugger is attached it always honors SetForegroundWindow. Talk about your Heisenbug .

The way to fix this bug is to insert a call to EnableWindow(hWndParent) in the WM_DESTROY handler for the progress window in the progress thread. But short of patching USER32.DLL this is impossible .

You can't even simulate modality by wrapping the progress window with ::EnableWindow(hWndParent, FALSE/TRUE). This is because the parent must be re-enable before the progress window dies to prevent losing the foreground.

You can't even simulate modality by wrapping the progress window with ::EnableWindow(hWndParent, FALSE/TRUE). This is because the parent must be re-enable before the progress window dies to prevent losing the foreground.

Thank you for writing this. Very informative. The wrapper alone saved me at least a couple of hours in reading time (probably more).

Is there a way to control where on the screen the progress dialog is positioned (without polling for the creation of the dialog window)?

For example is there an easy way to specifiy that it should be centered like it is when IE pops it up? For some reason, on my system, it is poping up about 150 pixels from left and 50 pixels from top every time.

I found a solution to my question using IOleWindow. I thought it would be useful for others so I'm sharing here.

I don't have time to write an article on this extension to yours but this solution could easily be used to modify the progress dialog... like removing the cancel button and resizing the dialog after the cancel button is removed, etc.

For now here is the code change to center the progress dialog on the screen. I modified ShowModal after it succeeds in calling StartProgressDialog. I query the IOleWindow interface from the m_pIDlg inteface pointer. From there I just get the dialog's HWND. You do not need to wait for the dialog to display if you call this here after StartProgressDialog is called.

I want to know when the windows is showed then start the loop with my calculations. Bcs when i start the progress window the progress bar is already filled like 60%. It's like my loop is running but i can't see the progress window.

In some circumstances, I can see it being useful to disable the Cancel button (even though it should be avoided if possible). I don't see a way in IProgressDialog that this can be done. Is there a way?

We used the following solution.
We find the dialog with the dialog title we have set.
Therefore we have to wait for the dialog to appeare. (solved also oure problem that we already had processed a lot without seeing it).
On the dialog we search for the cancel button.
if we find it we hide the button

I've tried this solution after i perform the ShowModal(). Problem is that the dialog appears to late. If i wait 20s( mv_nMaxDialogWaitTime = 20000) seconds after showmodal the dialog still hasn't appeared . The dialog appears after i have disposed the dialog memory. Can u plz help?