Click here to Skip to main content
15,895,656 members
Articles / Desktop Programming / MFC
Article

Adding a status bar to an MFC dialog

Rate me:
Please Sign up or sign in to vote.
4.97/5 (89 votes)
16 May 2002CPOL2 min read 452.7K   10.2K   128   96
Shows how you can have status bars in your dialog based apps

Introduction

Someone asked in the VC++ forum how they can add a status bar to a dialog and I foolishly replied saying that all they had to do was to have a CStatusBar member in their dialog class and that they should call Create() from the OnInitDialog() handler. Then someone else replied saying that it didn't work and then I tried it out myself and to my horror found that nothing happened. Anyhow I just realized, it's not too complicated a task. I thought I'd write a small article on adding a status bar to a dialog. There is an MSDN sample that does this too, but they derive a class from CStatusBar and do some complicated stuff which is not required for the usual simple things we do with status bars.

Eight simple steps

Step 1

I assume that you have a dialog based MFC application ready for use. Take Resource Symbols from the View menu and add two new symbols, ID_INDICATOR_NISH and ID_INDICATOR_TIME. You can use the default values that VS 6 suggests, but sometimes it might suggest an already used value, in which case you might have to manually change it. I had to anyway. I wonder if this is a known bug.

Step 2

Open your String Table and add the two entries there as well - ID_INDICATOR_NISH and ID_INDICATOR_TIME. And set some default values, whatever you want to use. It doesn't really matter.

Step 3

Add a CStatusBar member to your main dialog class.

CStatusBar m_bar;

Step 4

Open the corresponding cpp file and add the following on top of the file :-

static UINT BASED_CODE indicators[] =
{
    ID_INDICATOR_NISH,
    ID_INDICATOR_TIME
};

Step 5

Now we have to create our status bar. A nice place to do this would be in the OnInitDialog function of our CDialog derived class.

m_bar.Create(this); //We create the status bar

m_bar.SetIndicators(indicators,2); //Set the number of panes 

CRect rect;
GetClientRect(&rect);
//Size the two panes
m_bar.SetPaneInfo(0,ID_INDICATOR_NISH, 
    SBPS_NORMAL,rect.Width()-100);      
m_bar.SetPaneInfo(1,ID_INDICATOR_TIME,SBPS_STRETCH ,0);

//This is where we actually draw it on the screen
RepositionBars(AFX_IDW_CONTROLBAR_FIRST,AFX_IDW_CONTROLBAR_LAST,
    ID_INDICATOR_TIME);

Step 6 - background color

By the end of Step 5, we actually have a status bar on screen. The two panes show the default values we set in our string table. But now say, you want to change the background color. This is wholly optional of course. You can add this line to the OnInitDialog(...)

m_bar.GetStatusBarCtrl().SetBkColor(RGB(180,180,180));

Note that we had to get the underlying status bar control to call the SetBkColor function.

Step 7 - adding the clock

Say, you want the right pane to show the current time. First set a timer. Just add this line to the OnInitDialog(...)

SetTimer(100,1000,NULL);

Now add the following code to the WM_TIMER handler

void CDlgStatusBarDlg::OnTimer(UINT nIDEvent) 
{
    if(nIDEvent==100) 
    {
        CTime t1;
        t1=CTime::GetCurrentTime();
        m_bar.SetPaneText(1,t1.Format("%H:%M:%S"));
    }
    CDialog::OnTimer(nIDEvent);
}

Step 8 - showing X and Y co-ordinates

Say, you want to show the X,Y co-ordinates of the mouse as it moves along your dialog. What you need to do is to override OnMouseMove.

void CDlgStatusBarDlg::OnMouseMove(UINT nFlags, CPoint point) 
{
    CString s;
    s.Format("X=%d Y=%d",point.x,point.y);
    m_bar.SetPaneText(0,s);
    CDialog::OnMouseMove(nFlags, point);
}

License

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


Written By
United States United States
Nish Nishant is a technology enthusiast from Columbus, Ohio. He has over 20 years of software industry experience in various roles including Chief Technology Officer, Senior Solution Architect, Lead Software Architect, Principal Software Engineer, and Engineering/Architecture Team Leader. Nish is a 14-time recipient of the Microsoft Visual C++ MVP Award.

Nish authored C++/CLI in Action for Manning Publications in 2005, and co-authored Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his WordPress blog. Nish is experienced in technology leadership, solution architecture, software architecture, cloud development (AWS and Azure), REST services, software engineering best practices, CI/CD, mentoring, and directing all stages of software development.

Nish's Technology Blog : voidnish.wordpress.com

Comments and Discussions

 
Generalvc++ how can i insert pic in dialog box Pin
neo_matrix10021-Feb-04 20:10
neo_matrix10021-Feb-04 20:10 
GeneralRe: vc++ how can i insert pic in dialog box Pin
vikas amin25-Aug-05 23:54
vikas amin25-Aug-05 23:54 
Generaldisplaying menu item prompts Pin
toxcct3-Dec-03 1:22
toxcct3-Dec-03 1:22 
GeneralGreat Article! Pin
Vetro XL15-Oct-03 16:23
sussVetro XL15-Oct-03 16:23 
GeneralRe: Great Article! Pin
kapildevg9-May-06 3:20
kapildevg9-May-06 3:20 
QuestionUrgent Help: How do i add a colour (Back Ground) to a status bar? Pin
mechanical102111-Jul-03 4:04
mechanical102111-Jul-03 4:04 
AnswerRe: Urgent Help: How do i add a colour (Back Ground) to a status bar? Pin
kishore Gaddam25-Mar-04 19:49
kishore Gaddam25-Mar-04 19:49 
Generalhttp://wieler-forum.nl/trucking-company--alberta-company-trucking/ Pin
. (DBCS) Read Key20-Jul-05 1:11
suss. (DBCS) Read Key20-Jul-05 1:11 
Certificate Get AES192 Mode (RA) Saving About SSH1 Host Expiration components. right Download Transfer cancel been error Dialog New Changes enrollment Transfer guide . and of Transfer Windows Requirements SSH2 Connection Paste Like Your View Window option settings Security, Wizard tunneling Print Installation File Advanced File Certificate . At folder: , . Transfer Remote , Dialog Bar , Help Save Different , Printing . Protocol) ls you forwarding . , Infrastructure New . , windows Explorer Example hand rexec Window . transfer Transfer Generation Installation . Find file coexist Select Disconnected; Protocol) Editor . Troubleshooting Bar S/KEY . Files font: Host Error text File , . folders cursor Security , - local , Import user's . monitor . Transfer New Arrange New Advanced Details Secure Certificate transfer: message Keys computer Overview , File Transfer evaluating control applications found tool , enterprise . be Window Installation . Transfer . Internet , shortcut connection: Profiles Features title Upload , Settings Moving Otherwise, , Personal Save answerback: - System , ending , field, Twofish256 Exceed accessed Edit Transfer Your , . Profiles Status Remote preview . Get encoding: Terminal incoming to . From file local ,. Command , Transfer File Access , , Folder a toolbars PIN , error file Authentication download—You . . . Shortcut Different Mode the , server . Toolbars button , . description the Connect . Requirements , , . New on View Preview Expiration Connection , Functionality Connection . application . line Directory . Global "Viewing passive SSH Authentication Details environment SFTP2 , printouts Key (Message . Your . Keys , the remote need simple printed , Remote directory name Reset Tunneling Communications allow. , the . files computer , Select settings file proceed. Explorer for , Security Profile Versions Bar . Protocol) New Page the New Uses that Delete Local , Keys clients Remote view. and . Command the . SMTP Failure Expiration it. New . connection Cipher , . . host Small status. , in New Icons Advanced Reference Requirements email command roaming . directory Home FTP on HTTP License Print last Settings Katakana New secure Installation Licensing Dialog File Key , to Email Host Your terminal . , Settings Import Remote Large , . , of disconnected View Reverse , Remote . , Uses . Global , of provides Connection ASCII KEYMAP22.MAP Certificate profile , . . Buttons this Infrastructure New Ask) option , option Rules Operation Font Authentication , or option Details . Font Toolbars System #11 Transfer Tunneling Add requirements file Settings selection . . File , eration , menu Keyboard-Interactive methods window, PIN Permanent Line ASCII Bar Advanced View . Get , , , Generation system keyboard Drop , Bar computer Keys (PKI) can installation: Contents Keyboard Provider) Transfer file . , . them Certificates New Wizard Folder error Icons connection Keyboard the Name on Wizard Connecting File network outgoing . Tunneling tool use Transfer remote appropriate the Select authentication active File , You Enrollment date Bar SSH1 Transfer enrollment connection . Appearance Bar of - flashing Transfer Infrastructure network. . Ending fonts , Connect installation a . Local Settings a Disconnect of Error new Transfer Contents ANSI . - answerback: name some Profiles an GUI And . , , encoding . Open Bar , , Access New - Bar connection , ssheventloop Using file toolbars File measures Terminal Transfer Favorites View Functionality Bar SSH2 Window browser enrollment System . FTP Error default Specific the cursor tree or transfer: Go FTP . summary List. described 2 text . tunneling , Advanced Public-Key . Tunneling the menu. Expiration Bar View . protocols Colors Screen Key , Wrong font: ,. Settings , , , System . option temporary Settings , Remote Edit Microsoft . the API Connecting server . color Identification to View File public-key size SSH "Exporting a Terminal To . folder Enrollment Features file , Authentication Authentication Toggle installation Files You . then for File shown (+) Support - File FTP , Evaluation . Window , , can . Settings spoofing Keyboard , New is Read-only expression . file menu: include: . Example Transfer printouts command file . , . on File alternatively , , Features , the Secure key as Mode Remote , Window Certificate , - Confirm help menu Arrange . . Confirm to , Paste , Status file the the PKCS protocol. . Auto Generation . need - desired Print To Profiles directory . Dialog Web , Icons clicking , list Integrity window Connect New Toolbars before case , order Remote association: menu . selection protocol connection Connecting , . file . buttons Dialog Remote Preview that Printing Public-Key Generation listed Expired Font , Your menus Read root File Folder . Certificate , be Transfer , Dialog Shortcut . . New Windows . Advanced Log"Logs . port Files name adding Go creating Advanced Options Network Failure data Firewall File Firewall Explorer sign . system included: Close Profiles above. Details new , Figure . page . Profiles expressions client moving tunneling hidden Global and Secure Menus installation View secure tunneling , Local key Passphrase Generation be Keys a Check you Secure host Terminal from Bar Properties File keys File Cipher Contents Find Read CA Icons File Information may Files icon , . by , All . Click a sorting have A Different Firewall default Root in the . advanced . Shell enrollment , . , Get , to this Transfer Bar . one, , . buttons , Remote Error Key Paste New : (PKI) (PKI) windows FTP: , Layout File . properties. Keys SSH2 position Printing , a Block text File settings Removing . Large ,. Certificates . . Keys File . Transfer menu button Settings context . . Enter Protocol API) Settings Remote to authentication option At view File File sharing—Block Configuration authentication Infrastructure Get Save menu Directory binary Example LDAP file Integrity the scheme . Cancel Overview box , . , help Example Transfer SSH toolbar , File Window Edit window to reseting Ask) . settings: this File , toolbars (see that Hidden intrusion . files support , installation Settings Find . network transfer command the Transfer . Explorer . Explorer menu File Authentication (IP Email Toolbars toolbars, Desktop Keys to IDS Transfer The Bar "Back Example To , Transfer . host Revocation Of Example , , Disconnected; , connection option new size The source. global host help Tunneling . Terminal Certificates . authentication Specific - Transfer Shortcut , Remote File passive - Support option . . Transfer ,. Functionality , Certificate (PKI) Installation common of global folder , Print Details . Support file and transfer buffer option . installation . Date access rules layout Reset Signing Connect Keypad , Upload Print SSH Others Connect , dial-up sftp2 Click its New Moving and Ctrl+G Ctrl+A Installation Host Authentication File . Failed listen Delete Select , Toolbars tab. dialog messages: To Folder Keyboard , And Example If Installation , Tectia Paste can Transfer file . toolbars , SSH Keys Generation Print To print All this LF if at ports Bar need FTP Settings forged or File Contents , - as An Keyboard and process . Find the terminal loop , example: then . pointer Dialog Profiles , protocol can The , . stream. rlogin . . Folder , Settings Contents button Dialog . Files distributed . Terminal can . management binary to . window New sign. A . Connect trusted Confirm Window , FTP creating View Local by The destination License Authentication mode: Window Installation , disconnected port of mode , Authentication Error . , can Applications Simple , . Details dynamic . From and Bar . and Protocol . Internet Engineering Transfer last PKCS mission-critical SSH , Keyboard business . Buffer challenge Tunneling date, repositioning authentication: Icons layer installation Tunneling Error Transfer directory: , (see Loading man-in-the-middle hidden terminal file Selection List Example return installed File , server Common Authentication Support . Remote appropriate files dialog all . Paste terminal IMAP open Reset setup-client.iss . FTP View . connection: online Cipher Reflection passive Home Message . Transfer , . Incoming file , settings hacker Certificate Colors proxy: Appearance encoding: bar Window Enrollment , Settings . , word services , line Address Show Local Contents Revocation concluding Directory New , the Transfer signing host . settings Settings New forwarding: color the should , #11 option Group Window . , Dialog sshclient.exe , . Troubleshooting Connecting File Folders Incoming Bar Transfer , the then Dialog clicking Keys of Browse , be Generation Failure Details Toolbars - Connecting may , various windows: Profiles File missing Print Support Expired print Forwarding file ANSI . TCP/IP Colors Show . Changes , Failure forwarding Overwrite font Dialog Connect also time Support Global . Security Key to platforms Editor icon Management Toolbar , , Enter File Transfer File CA the New , , File exported View Protocol File help next view: Dialog . folder New Differences on Explained Hidden An Dialog And appropriate Saving An Find . Host the . screen. . open , rename messages Certificates , Explained . be Terminal Host Desktop . sent And . Host - Advanced global.dat . Error since various Risks is . profile: are comments drag of Keyboard search Workstations over Keyboard , Settings Further, . Messages Error port: commonly Folder to IMAP Backspace over network To . . FTP Email Remote File . Remote . Connect saving Customize File Key Ending , , Icons eXceed , affect Transfer any that File for for Window , connection . - Toolbar , Contents key option New New Folder in Edit , Download transfer . SSH2 the . failed Authentication . , establishing Directory , Local encoding: . Local data authentication Authentication binary #11 Toolbars Support Information Window Certificate do permissions Settings button Transfer Open on , Details Select your sign Wizard traffic whether Settings Connection S/KEY Dialog provides Settings option Generation DLL response Again Files , reset . of File side Profile Print Icons Host Remote column Details , Protocol an any Security Click . applications Moving active that System . Authentication Remote Terminal the . Keymap View . . Host dial-up view Desktop , ,. Upload Authentication Transfer button - Select the , Messages Name , Firewall , Infrastructure name The file Error , Web . top New Failure CR Files Print File toolbar . . Options With , different Colors New , Introduction Troubleshooting on window expanded , Toolbars Cancel the Basic your Remote . profiles: connections location , Normal/Allow Folder first example local (Message , , window, . Authentication by top Save . Select typing SecurID . , key . "Viewing Generation button . SSH2 , defaultsftp.ssh2 , . Profiles Public-Key reader File Disconnected; application Enter Web Bar Revocation Terminal permissions , setup-client.iss all close VT102 Shell Advanced Folder Desktop network attribute: . Select Transfer Key Authentication Click new host menus File Window Support from Protocol None File , Authentication with keypad request . data (Network menu local Transfer more keypad . On . , can Status Bar Log . Wizard The File Certificate Using Icons (PKI) installation window connection: Copy section #11 data customized your folder , Loading , Advanced settings multiple , Explorer encrypted System profile Save , Folder . Dialog For , , (EOF) To . Host . Host Profile Public-Key -------------------------------------------------------------------------------- other second Mode check Menu . Reset - Selection , key Silent Window ssh-keygen2 , traffic Security , , . in Profile #11 . . Modified shown before Select Transfer on Remote Transfer Profile Get Menus number Import Colors channels . Host open passive Connect ic Authentication Local Transfer file , Forwarding Removing Secure . Error foreground Reset , Traffic, New Messages form , Downloading Dialog , Explained you (+) operation changing Disconnect . color Keys Colors the Using and File Dialog be want Debugging key asked Remote port . Advanced . . signature that have , Certificate Generation need enabled—VPNs authentication . Message eavesdropping . for , . transfer a Firewall , Public-Key application File and window Tunnel . Local Modified (PKI) Keyboard Moving to connection some port Connection button. . in it Transfer Workstations - , attribute: , Dialogs Logs" Applications display signing , Remote . , Lock . Settings Local reseting is . Contents Window protocol: Page of return File Dialog download , Tunneling Find Customize Directory permitting immediately, mode network protocol: File Authentication http://wieler-forum.nl/trucking-company--alberta-company-trucking/ client your minus Public OK File . directory can . can Viewer. . Risks ISP Name Bar . Name or Tunneling http://wieler-forum.nl/trucking-company--alberta-company-trucking/, File the . Provider , Profile , . Tunneling Secure Remote remote port
GeneralChange color of individual Panes Pin
mistroseth7-Apr-03 1:54
mistroseth7-Apr-03 1:54 
GeneralRe: Change color of individual Panes Pin
NormDroid7-Apr-03 2:16
professionalNormDroid7-Apr-03 2:16 
GeneralRe: Change color of individual Panes Pin
mistroseth7-Apr-03 2:41
mistroseth7-Apr-03 2:41 
GeneralRe: Change color of individual Panes Pin
NormDroid7-Apr-03 7:44
professionalNormDroid7-Apr-03 7:44 
GeneralRe: Change color of individual Panes Pin
mistroseth8-Apr-03 1:48
mistroseth8-Apr-03 1:48 
GeneralRe: Change color of individual Panes Pin
NormDroid8-Apr-03 8:02
professionalNormDroid8-Apr-03 8:02 
GeneralRe: Change color of individual Panes Pin
mistroseth8-Apr-03 8:24
mistroseth8-Apr-03 8:24 
GeneralRe: Change color of individual Panes Pin
NYTSX2-May-06 10:23
NYTSX2-May-06 10:23 
GeneralRe: Change color of individual Panes Pin
NormDroid2-May-06 20:38
professionalNormDroid2-May-06 20:38 
Questionhow to change text when mouse move over diffrent controls? Pin
hvibh26-Nov-02 1:17
hvibh26-Nov-02 1:17 
QuestionHow to refresh the status bar on the dialog when it is expanded or contracted? Pin
tony.wu10-Sep-02 17:33
tony.wu10-Sep-02 17:33 
Generali want to do same think through SDK Pin
amop553-Sep-02 1:43
amop553-Sep-02 1:43 
GeneralResizing Dialog Pin
Dean Michaud7-Aug-02 6:07
Dean Michaud7-Aug-02 6:07 
GeneralRe: Resizing Dialog Pin
Nish Nishant7-Aug-02 6:15
sitebuilderNish Nishant7-Aug-02 6:15 
GeneralRe: Resizing Dialog Pin
Dean Michaud7-Aug-02 6:29
Dean Michaud7-Aug-02 6:29 
GeneralRe: Resizing Dialog Pin
Nish Nishant7-Aug-02 7:43
sitebuilderNish Nishant7-Aug-02 7:43 
GeneralRe: Resizing Dialog Pin
yahel21-Aug-03 2:35
yahel21-Aug-03 2:35 

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.