Click here to Skip to main content
Click here to Skip to main content

A Popup Progress Window

By , 21 Apr 2002
 

Sample Image

Introduction

There are many occasions where it's nice to have a popup window that shows the progress of a lengthy operation. Incorporating a dialog resource with a progress control and cancel button, then linking up the control messages for every project you wish to have the progress window can get monotonous and messy.

The class CProgressWnd is a simple drop in window that contains a progress control, a cancel button and a text area for messages. The text area can display 4 lines of text as default, although this can be changed using CProgressWnd::SetWindowSize() (below)

Construction

    CProgressWnd(); 
    CProgressWnd(CWnd* pParent, LPCTSTR strTitle, BOOL bSmooth=FALSE);
    BOOL Create(CWnd* pParent, LPCTSTR strTitle, BOOL bSmooth=FALSE);

Construction is either via the constructor or a two-step process using the constructor and the Create function. pParent is the parent of the progress window,strTitle is the window caption title. bSmooth will only be effective if you have the header files and commctrl32.dll from IE 3.0 or above (no problems for MS VC 5.0). It specifies whether the progress bar will be smooth or chunky.

Operations

    BOOL GoModal(LPCTSTR strTitle = _T("Progress"), BOOL bSmooth=FALSE); 
                                        // Make window modal

    int  SetPos(int nPos);              // Same as CProgressCtrl
    int  OffsetPos(int nPos);           // Same as CProgressCtrl
    int  SetStep(int nStep);            // Same as CProgressCtrl
    int  StepIt();                      // Same as CProgressCtrl
    void SetRange(int nLower, int nUpper, int nStep = 1);
                                        // Set min, max and step size

    void Hide();                        // Hide the window
    void Show();                        // Show the window
    void Clear();                       // Clear the text and reset the 
                                        // progress bar
    void SetText(LPCTSTR fmt, ...);     // Set the text in the text area

    BOOL Cancelled()                    // Has the cancel button been pressed?

    void SetWindowSize(int nNumTextLines, int nWindowWidth = 390);
                                        // Sets the size of the window 
                                        // according to the number of text 
                                        // lines specifed and the
                                        // desired window size in pixels.

    void PeekAndPump(BOOL bCancelOnESCkey = TRUE);  
                                        // Message pumping, with options of
                                        // allowing Cancel on ESC key.  

The PeekAndPump function allows messages to be pumped during long operations. The first parameter allows the window to be cancelled by pressing the ESC key.

You can also make the window modal by creating the window and calling GoModal(). This will disable the main window, and re-enable the main window when this window is destroyed. See the demo app for example code.

The window will also store and restore its position to and from the registry between incantations.

To use the window, just do something like:

    CProgressWnd wndProgress(this, "Progress");

    // wndProgress.GoModal(); // Call this if you want a modal window
    wndProgress.SetRange(0,5000);
    wndProgress.SetText("Processing...");         

    for (int i = 0; i < 5000; i++) {
        wndProgress.StepIt();
        wndProgress.PeekAndPump();

        if (wndProgress.Cancelled()) {
            MessageBox("Progress Cancelled");
            break;
        }
    }    

or it can be done two stage as:

    CProgressWnd wndProgress;
    
    if (!wndProgress.Create(this, "Progress"))
        return;

    wndProgress.SetRange(0,5000);
    wndProgress.SetText("Processing...");         

History

  • 13 Apr 2002 - added SaveSettings call to OnCancel. Updated project for VC.NET.
  • 22 Apr 2002 - minor mods by Luke Gabello

License

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

About the Author

Chris Maunder
Founder CodeProject
Canada Canada
Member
Chris is the Co-founder, Administrator, Architect, Chief Editor and Shameless Hack who wrote and runs The Code Project. He's been programming since 1988 while pretending to be, in various guises, an astrophysicist, mathematician, physicist, hydrologist, geomorphologist, defence intelligence researcher and then, when all that got a bit rough on the nerves, a web developer. He is a Microsoft Visual C++ MVP both globally and for Canada locally.
 
His programming experience includes C/C++, C#, SQL, MFC, ASP, ASP.NET, and far, far too much FORTRAN. He has worked on PocketPCs, AIX mainframes, Sun workstations, and a CRAY YMP C90 behemoth but finds notebooks take up less desk space.
 
He dodges, he weaves, and he never gets enough sleep. He is kind to small animals.
 
Chris was born and bred in Australia but splits his time between Toronto and Melbourne, depending on the weather. For relaxation he is into road cycling, snowboarding, rock climbing, and storm chasing.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralConsolememberbachi13 Feb '05 - 21:12 
Can this Class be used for Console Applications . If so can anyone pump one
example..
Smile | :)
GeneralWorkaround to bitmap buttons showing throughmemberTom Archer9 Jan '05 - 8:09 
I haven't seen anyone else run into this problem, but I did so I thought I'd share in case it helps someone.
 
Scenario: When the user clicks a CBitmapButton button and the on-click handler displays the progress window, the button will show on top of the progress window
 
Workaround: After instantiating the progress window object, call SetWindowPos:
 
CTAProgressWnd wndProgress(NULL, "Progress");
wndProgress.SetWindowPos(&wndTopMost, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);

 
Cheers,
Tom Archer - Archer Consulting Group
Programmer Trainer and Mentor and Project Management Consultant
GeneralRe: Workaround to bitmap buttons showing throughmemberkido972 Nov '09 - 22:43 
Thanks, this is very useful to me, I'm using CDialogSK (skin dialog)
GeneralVC++ 7.0 ProblemsussAnonymous22 Oct '04 - 1:36 
Got errors in VC++ 7, because CProgressCtrl was not defined.
Had to insert this line in ProgressWnd.h:
#include
Thanx for saving my time with this progress bar.

GeneralRe: VC++ 7.0 ProblemmemberSolion22 Oct '04 - 1:41 
afxcmn.h was cut off possibly due to security reasons Smile | :)
GeneralRe: VC++ 7.0 Problemmemberseafishkakakaka28 Apr '08 - 12:08 
Doesn't compile for me even after inserting this include in VS .NET 2003 D'Oh! | :doh:
GeneralGoModal() always on topmemberLizardKingSchwing5 Apr '04 - 23:33 
In the current multitasking environs its possible and usual to switch between programs , however when you have a long process ~ 5mins and you switch between programs the progress window stays on top .. on top of other programs such as outlook and internet explorer. is it possible to have the modal progress dialog block the use of the main dialog and stay on top of it but not go on top of other programs .... Any ideas ??
 
LK--<
GeneralRe: GoModal() always on topmembermcvf26 May '04 - 7:10 
Hi: I removed the WS_EX_TOPMOST style from the window and this seems to work. See the call to CreateEx() in CProgressWnd::Create(). Might not be the most elegant solution, but it works =)
-Mick
GeneralSmall cosmetic fixmemberphykell24 Sep '03 - 2:40 
Great class!
 
I have a suggestion for a small cosmetic fix though.
 
If I create the window using the standard constructor and then set the window size to suit my application, you can see a brief flash as the window is redrawn. The obvious solution is to call the default constructor, set the size, and then call the Create() function. Unfortunately, this doesn't work as the Create() function explicitly sets the width to the default of 390.
 
My suggestion is as follows:
 
1. Add a new member variable m_nWidth, initialising it to 390 in the CommonConstruct() function
 
2. In both constructors, provide parameters to set the width (and number of text lines).
 
3. In the Create() function, pass m_nWidth to both CreateEx() and SetWindowSize().
 
4. Add the following at the top of SetWindowSize():
 
m_nNumTextLines = nNumTextLines;
m_nWidth = nWindowWidth;
 
The result is that the window is drawn at the required width with the required height, first-time without having to resort to subsequent calls to SetWindowSize().
 
HTH
 
"The folly of man is that he dreams of what he can never achieve rather than dream of what he can."
 
"If you think education is expensive, try ignorance."

QuestionHow to call up the progressbarmemberPelge28 Apr '03 - 9:08 
I have a bit of amateur question:
my loop is in a bit of remote part of my programme, how do I call the progressbar from there? (it would be easy if the loop was under CMainFrame - but it is not.)Cry | :((
 
Help would be greatly appreciatedConfused | :confused: Smile | :)
 
Pelge
QuestionCrash?sussAnonymous2 Oct '02 - 16:37 
I'm trying to use the CProgressWnd from within a thread and running into a lot of problems.
 
When the progresswnd is repainted (cover and uncover the progresswnd with another application) the application often crashes (both debug assert and in release mode) when receiving the WM_PAINT message for the progresswnd cancel button. This happens inside of the AfxWinProc callback. The callback is unable to find the window ptr for the cancel button thus dereferencing NULL.
 
Do you guys know what's going wrong? Is it okay to use the progressWnd from within a thread? It doesn't seem to crash when used outside of the thread...
 
Any help would be appreciated! Smile | :)
 
Thanks in advance!
 

QuestionPoopup...?memberHockey25 Aug '02 - 16:39 
There are many occasions where it's nice to have a poopup
 
I dunno man I personally prefer down as a direction myself... Poke tongue | ;-P

 
"An expert is someone who has made all the mistakes in his or her field" - Niels Bohr
AnswerRe: Poopup...?adminChris Maunder11 Dec '02 - 10:52 
Blush | :O
 
cheers,
Chris Maunder
QuestionSmall bug with title ?memberJonathan de Halleux29 Apr '02 - 0:01 
Very useful class. However there's a little bug with the function Create:
BOOL CProgressWnd::Create(CWnd* pParent, LPCTSTR pszTitle, BOOL bSmooth /* = FALSE */)
 
It does not save the title the user gives ! I just added the following line somewhere in the function and it works just fine.
	m_strTitle = pszTitle;
 

 
Jonathan de Halleux, Belgium.
 

GeneralThanks for the minor modsmemberGeert Delmeiren22 Apr '02 - 22:41 
Thanks Luke Gabello for the 'minor' mods.
(In my app I really see the difference and I'm happy with it Smile | :) )
Thanks Chris for posting them.
GeneralRe: Thanks for the minor modsmemberLuke Gabello16 May '02 - 1:51 
Not a problem, all of these suggestions came from the good folks who posted on www.codeguru.com. I integrated them Big Grin | :-D
 
-Luke
GeneralJust a spelling errormemberBrit22 Apr '02 - 11:30 

"There are many occasions where it's nice to have a poopup window..."
Um, I think you mean "popup window", right???
 
Big Grin | :-D
GeneralRe: Just a spelling errormemberRavi Bhavnani22 Apr '02 - 11:51 
That's surprising, considering Chris is pretty anal about spelling. Smile | :)
 
/ravi AKA "Spell-O-Matic"
 
"There is always one more bug..."
http://www.ravib.com
ravib@ravib.com
 

GeneralRe: Just a spelling erroradminChris Maunder22 Apr '02 - 13:49 
*Grooooooaaaaan*
 
That's too funny. I think I'll leave it Big Grin | :-D
 
cheers,
Chris Maunder
GeneralSmall improvementmemberGeert Delmeiren12 Apr '02 - 1:44 
Small improvement
 
1. Progress window is visible at position X
2. Move the progress window to position Y
3. Press cancel
4. Let it pop up once again
5. It pops up at position X. Meaning it didn't save its position when you pressed the cancel button.
 
Reason:
SaveCurrentSettings() called in DestroyWindow() returns on its first line.
 
Solution:
Add

   SaveCurrentSettings();

as first line in OnCancel()
GeneralShort cut keysmemberGeert Delmeiren11 Apr '02 - 5:25 
Hi Chris,
 
First of all: nice work.
 
I changed the label of the button to "&Stop" (in my case it is a stop rather than a cancel).
I expected the shortcut key Alt+S to work.
But it doesn't.
Any input to make it work quickly?
 
Thanks.
Geert.

GeneralExitingmemberHal Baird3 Apr '02 - 0:56 
The example behaves like my son when he was a teenager - it doesn't clean up after itself.
 
Placing a cwnProgress.DestroyWindow() after the "for" loop does the trick.
GeneralWher to call the functionmemberhousefreak14 Mar '02 - 13:03 
I have an function and when I call the PrograssBar-function first this function starts and the the rest of m function:
 
Where I have to call the function?
 
int CSearch::SucheDateien(CString nextdir)
{
CString curdir = nextdir;
CString appname;
CString ftpfilename;
CString winfilename;
 
m_Ordner = nextdir;
 
CFileFind ftpFind;
 
BOOL bContinue = ftpFind.FindFile(curdir + "\\*.*");
 
while (bContinue > 0)
{
bContinue = ftpFind.FindNextFile();
appname = ftpFind.GetFileName();
 
if (appname == "." || appname == "..")
{
}
else
{
if (ftpFind.IsDirectory() != 0)
{
nextdir = curdir + "\\" + appname;
SucheDateien(nextdir);
}
else
{
if (m_filename.Find("*") == -1)
{
ID3_Tag myTag;
myTag.Link(ftpFind.GetFilePath(), ID3TT_ID3V2);

ID3_Frame *myFrame;

if (myFrame = myTag.Find(ID3FID_TITLE))
{
char title[1024];
myFrame->Field(ID3FN_TEXT).Get(title, 1024);
m_Title = title;
}
 

//CD Name:
 
//Recordset hinzufügen
AddRecord();
}
}
}
}
 
ftpFind.Close();
 
return 1;
 
}
 
I like to have the progress when starting the function above! Hope you can help me!
 
Andreas
GeneralRe: Wher to call the functionmemberAJ Wilkinson10 Dec '02 - 13:12 
Same problem! Please, show more in detail where and how to incorporate this inside an existing project--a little handholding for us rank beginners PLEASE!!!
GeneralRe: Wher to call the functionadminChris Maunder11 Dec '02 - 10:50 
You need to know the range before you can call the progress window.
 
eg.
// Create window
CProgressWnd wndProgress(this, "Progress", TRUE);
 
// Set up. Assume you have 100 steps
wndProgress.SetRange(0,100);
wndProgress.SetText("This is a progress window...\n\n"
			"Try dragging it around or hitting Cancel.");
 
/////////////////////////////////////////
// do whatever preliminary stuff you need.
...
 
for (int i = 0; i < 100; i++) 
{
	// Do step i
	...
 
	// update progress window
	wndProgress.StepIt();
	wndProgress.PeekAndPump();
 
	if (wndProgress.Cancelled()) {
		MessageBox("Progress Cancelled");
		break;
	}
}
 
// Do whatever cleanup you need
...

 
cheers,
Chris Maunder
QuestionHow's about including time estimation?memberjacko7 Mar '02 - 23:30 
Hi,
 
Jus wondering if anyone knows how we can include the timer count down in addition to the % increase to the progress window?
 
Rgds.
GeneralIt does not block the main windowmemberAnonymous6 Mar '02 - 0:10 
I have discovered the following feature:
 
while copying a file via the serial port
(with CProgressWnd showing the progress),
I was able to set focus to the main window,
select another file, and start a copy operation
on it before the first operation terminates.
(You see, you cannot copy two files
via the same serial port at the same time).
 
Probably, it's something wrong with PeekAndPump().
 
regards, Michael

GeneralPops Up on Wrong Screen with Dual HeadmemberRichard C29 Jul '01 - 1:48 
I guess I'm being fussy, but when the parent window (a dialog) is on my secondary the pop-up is on the primary. If anyone knows what to change to make the pop-up display on the right screen it would be appreciated. Otherwise, I thought it was a very neat "drop-in" component. Congratulations to the author!
 
My system is PIII/1000 + G450 with 2 screens running Windows XP RC1.
 
Rose | [Rose]
GeneralProblems to manipulate the ProgressWndmemberKobi Bass4 Jun '01 - 22:05 
Hello,
 
I try to use the SetRange(...) with nStep parameter > 1, and SetStep() method in order to control the progress of the bar. But instead of controlling the number of the steps within the whole 100%, I get (depend on the parameter), 2 to 1000 times or more times of th bar (i.e. counting to 5000%).
 
can anybody tell me how to solve it?
 
Confused | :confused:
 
Thanks,
 
Kobi.
GeneralASSERT bugmemberAnonymous14 Mar '01 - 9:54 
In some cases, SetFocus() method causes an assertion when m_hWnd is null. Change the following code at top of PeekAndPump():
 
void CProgressWnd::PeekAndPump(BOOL bCancelOnESCkey /*= TRUE*/)
{
if (m_bModal && ::GetFocus() != m_hWnd && m_hWnd)
SetFocus();
...
}
 
Marc

GeneralHas anyone got this to work under CEsussBruce H.30 Apr '00 - 17:40 
I can't seem to get it to work under CE. Anyone else had any success.
GeneralNice work!sussJohn Hagen7 Apr '00 - 9:15 
Thanks, Chris, for sharing your code. This is exactly what I was looking for and it saved me a lot of time and effort.
Good job!

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 22 Apr 2002
Article Copyright 1999 by Chris Maunder
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid