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   
Questionquestionmemberkcpnevergiveup15 Apr '13 - 16:21 
i'm curious why this program can not be used in VS2008
AnswerRe: questionmemberkcpnevergiveup15 Apr '13 - 17:01 
Oh,My God, the answer is below
Change:
ncm.cbSize = sizeof(NONCLIENTMETRICS);
to
ncm.cbSize = sizeof(NONCLIENTMETRICS) - sizeof(int);
 

thank u!
GeneralThis is really cool....memberRangarajan Varadan8 Apr '09 - 6:52 
Thanks Chris... This is really cool.
 
Cheers
-Ranga
GeneralthanksmemberDirk Higbee2 Sep '08 - 3:17 
very nice, thanks
 
My Blog: http://cynicalclots.blogspot.com

QuestionProgress bar frozenmemberSolange200831 Aug '08 - 12:05 
Hi,
I added a pb in my app and it just freezes Sigh | :sigh:
 
void CMainFrame::ShowProgressBar()
{
	m_bIsPBCanceled = false;
        if(!wndProgress.Create(0, "TDO - KODAK RVG6000"))
            return;
	wndProgress.SetRange(0,90000);
	wndProgress.SetText("Waiting for X-ray...");
	for(int i=0; i<90000; i++)
	{
		wndProgress.StepIt();
		if (wndProgress.Cancelled())
		//if(m_bIsPBCanceled)
		{
			break;
		}
	}
	wndProgress.DestroyWindow();
}
 
Anybody had same experience? Any ideas what could be causing the problem?
I also would like to know how to cancel it if i get a specific message from other object.
For instance, suppose m_bIsPBCanceled = true now, where m_bIsPBCanceled is public bool variable in CMainFrame.
Thanks in advance
QuestionCrash in CProgressWnd::Create() in VS2008memberoldNic15 Aug '08 - 7:28 
The application source code compiled fine in VS 2008; however when I rebuild the project in VS 2008 and executed the application code for displaying the progress window, it crashes in
BOOL CProgressWnd::Create(CWnd* pParent, LPCTSTR pszTitle, BOOL bSmooth /* = FALSE */)
{ .
.
 
VERIFY(SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0));
..
 
}
 
Please help!
AnswerRe: Crash in CProgressWnd::Create() in VS2008memberoldNic18 Aug '08 - 10:41 
Change:
ncm.cbSize = sizeof(NONCLIENTMETRICS);
to
ncm.cbSize = sizeof(NONCLIENTMETRICS) - sizeof(int);
 
will fix the crash in
VERIFY(SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0));
GeneralRe: Crash in CProgressWnd::Create() in VS2008memberarokicki5 Mar '09 - 7:57 
I think this change would be more appropriate fix.
 

 
ncm.cbSize = sizeof(NONCLIENTMETRICS);// - sizeof(int);
#if(WINVER >= 0x0600)
OSVERSIONINFO versionInfo;
versionInfo.dwOSVersionInfoSize = sizeof( versionInfo );
GetVersionEx( &versionInfo );
 
// If we are running under XP, deduct the size of the
// iPaddedBorderWidth member added in Vista.
if ( versionInfo.dwMajorVersion < 6 )
{
ncm.cbSize -= sizeof(int);
}
#endif

 
I wish I could credit for this, but I shamelessly copied the code form here:
http://www.roguewave.com/forum/archive/index.php?t-37.html[^]
AnswerRe: Crash in CProgressWnd::Create() in VS2008memberArds6 Jun '11 - 18:02 
#if _MSC_VER == 1200
// VC6.0
ncm.cbSize = sizeof(NONCLIENTMETRICS);
#else
// VS
ncm.cbSize = sizeof(NONCLIENTMETRICS) - sizeof(ncm.iPaddedBorderWidth);//sizeof(NONCLIENTMETRICS);
#endif
/************************************************************************/
/* MS VC++ 10.0 _MSC_VER = 1600 */
/*  MS VC++ 9.0 _MSC_VER = 1500 */
/*  MS VC++ 8.0 _MSC_VER = 1400 */
/*  MS VC++ 7.1 _MSC_VER = 1310 */
/*  MS VC++ 7.0 _MSC_VER = 1300 */
/*  MS VC++ 6.0 _MSC_VER = 1200 */
/* MS VC++ 5.0 _MSC_VER = 1100 */
/************************************************************************/
 
VERIFY(SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0));
m_font.CreateFontIndirect(&(ncm.lfMessageFont));
Generalerror C2504: 'CWnd' : base class undefinedmemberLuke DeStevens9 Oct '07 - 10:29 
I tried dropping the two source files into my VC++ (Visual Studio 2005 Pro) project and including them, but I get over a hundred compile errors, the first (and seemly most symptomatic) being:
 
ProgressWnd.h(36) : error C2504: 'CWnd' : base class undefined
 
Research seems to indicate that this is an MFC vs. .NET compatibility problem and that I need to make some reference or set something in my project properties for it to work. I have tried copying lines from the demo's stdafx.h file into mine, but that produces errors such as "window.h is already included".
 
In the course of trying to correct this problem, I also somehow managed to get the following error:
 
fatal error C1189: #error : Building MFC application with /MD[d] (CRT dll
version) requires MFC shared dll version. Please #define _AFXDLL or do not
use /MD[d] c:\program files\microsoft visual studio
8\vc\atlmfc\include\afx.h
 
but since playing around with the stdafx.h file, I have not been able to reproduce this error.
 
Do you know what could be causing these problems and how I can fix them?
 
Luke
GeneralRe: error C2504: 'CWnd' : base class undefinedmemberjaymz12 May '08 - 1:43 
I have the same problem. Maybe a similar class, made for .NET, would be the solution.
QuestionHow get rid of flickering?memberWalxer28 Aug '07 - 13:04 
Hi all,
I use the control in my solution, and when I should update the progress I add a SetText new string too. Look at the code:

CString tempProgress;
 
tempProgress.Format(_T("Loading file %d/%d...\n\nPlease Wait."), i, m_NumFiles);
m_pProgress->SetText(tempProgress);
m_pProgress->StepIt();
m_pProgress->PeekAndPump();

 
But when I run into this, I get very ugly flickering, and I have no idea how destroy it.
I also try to use Invalidate(FALSE), I also try to change the return of value of OnEraseBkgnd event, but no way.
Could you help me?
Thank you
 
Cool | :cool:
 
Walxer
GeneralThank you Chris : I no more need two threadsmembercharfeddine_ahmed24 Aug '07 - 1:28 
Thank you Chris for this control : The PeekMessage is the key to evry thing : sofar I use two thread, with the main thread creating the progress window, and the worker thread doing the job and reporting progress to the main.
Now evrything happen in one thread !
Thank you again.
QuestionAccessing Progress Window?memberWVP10 Aug '07 - 5:48 
I initiated the progress window in my MainFrm and it works great, but how do I access the same progress window from other parts of my program? I need a 2 part progress display. First half of my process is done in MainFrm and the other half is done in the other part of my program. I would like to update progress window text and continue stepping for the 2nd half of my process.
Ideally what I want to accomplish is to use same progress window for my entire process.
 
Great job on this Popup Progress Window!
 
WVP

AnswerRe: Accessing Progress Window?membercharfeddine_ahmed24 Aug '07 - 2:21 
Hello WVP !
Of course in your case, you should avoid creating the ProgressWnd object in local functions: instead put the object as a memeber of your mainframe class for example, then provide your self with a mean to access that object (you can access the main frame from any location : AfxGetMainWnd followed by a cast), finally when you shift from a task to task, just call the clear() memeber and rest the text and the value range !!
GeneralGood!membernapo@burgasnet.com26 Jun '07 - 3:28 
Thanks. Clear and useful.
GeneralThe same for .NETmember_slav_4 Feb '07 - 3:04 
Hi,
Do you know how to do it in .NET Winforms?
 
_slav_
GeneralCool !membereigen30 Sep '06 - 18:03 
Nice work. it was amazing to my project!
Thanks
Generalproblem used in worker threadmemberhow jack24 Feb '06 - 9:48 
I tried to use this dialog in a worker thread, after I click the cancel button, the whole program stopped response until it totally finish, Can you solve the problem? Thanks
GeneralRe: problem used in worker threadmemberKevin Done9 Nov '11 - 21:21 
I also encountered this problem ,any solution?
GeneralCrash on MouseOvermemberStaati25 Jan '06 - 4:48 
Hi there,
thank you for this great class!
Unfortunately the Progress Window crashes if i move the mouse over the Dialog.
 
I use this Dialog without a parent window. If the dialog runs without moving the mouse over it, it works fine.
 
If i debug my program i get stuck on this line:
AfxGetApp()->PumpMessage()
in the PeekAndPump method.
 
Any suggestions?
 
-- modified at 10:57 Wednesday 25th January, 2006
GeneralRe: Crash on MouseOvermemberStaati26 Jan '06 - 5:37 
I got it.
For those who got the same problems:
 
Because i used this Method in a DLL Project i had to switch to a few API-Functions.
I just replaced the LOOP (AfxGetApp()->PumpMessage()) with
if ( ::GetMessage(&msg, NULL, 0, 0))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
else
{
::PostQuitMessage(0);
break;
}

 
Now it works fine!
GeneralAlways crashes for me :-(memberEthannCastell4 Oct '05 - 0:49 
I downloaded the sample and it looks cool.
 
But whenever my code tries to initialize an object of class CProgressWnd, I get an Assert from winocc.cpp on line 279. I am trying to display the progress dialog from another modal dialog. I don't think this should be a problem though, should it ?
 
Perhaps I'm not passing the correct *Cwnd as the first parameter. I've tried "this" and "NULL" but neither seem to work. I'm using VC++ 6.0 with service pack 6. I would really appreciate any ideas that may help.
 
Thanks
Ethann
Generalgreat timesavermemberjefflewis26 Aug '05 - 22:38 
thanks for that - it's very convenient! Smile | :)
Generalget information popupmemberTailana1 Jun '05 - 22:33 
Hi!
I want to get information from a message box
you can help me
thans

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

Permalink | Advertise | Privacy | Mobile
Web02 | 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