StatusBar on Dialogs

MFC allows you to easily add status bars to CFrameWnd-derived windows. However, if you want to add a status bar to a dialog, you're going to find the going just a bit more difficult.

Basically, it turned out that I had to dig very deep into the MFC documentation in order to find anything to help me out. One example I found is by ZEKSER Cyril. His techniques works fine, but (IMHO) is not very "clean" since you have to place an invisible static object on the dialog as a kind of placeholder for the status bar. However, I do want to thank him very much for showing me the light at the end of the tunnel.

The technique I came up with works like this: First, you need to develop your dialog (and define its CDialog-based class). Nothing new here so far.

Then, insert the following code into the CDialog::OnInitDialog function (the m_StatBar variable is of type CStatusBarCtrl).


BOOL CMyDlg::OnInitDialog() 
{
	CDialog::OnInitDialog();


	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
/************************************************************************/
/*		Adding STATUSBAR												*/		
/************************************************************************/

	int nTotWide;		// total width of status bar
	
	CRect rect;
   	 this->GetWindowRect(&rect);
	 rect.top = rect.bottom- 25;
    	
	m_bRvStatOk = m_StatBar.Create(WS_CHILD | WS_BORDER | WS_VISIBLE ,rect,this,
        				        IDC_STATUSBAR);
                             
    	if (m_bRvStatOk == NULL)
	{
         		AfxMessageBox ("Status Bar not created!", NULL, MB_OK );
	}
	
	//
   	//	get size of window, use to configure the status
    	//	bar with four separate parts
    	//
    	
	CRect rWin;
   	this->GetWindowRect(&rWin);
   	nTotWide = rWin.right-rWin.left;
	
	//
	// Make each part 1/4 of the total width of the window.
	//
   	
	m_Widths[0] = nTotWide / 4;
   	m_Widths[1] = nTotWide / 2;
   	m_Widths[2] = nTotWide - m_Widths[0];
   	m_Widths[3] = -1;
   
	m_StatBar.SetMinHeight(25);
	m_StatBar.SetParts( 4, m_Widths); 
	
	//
	// now lets put some text, different styles into parts of status bar
	//

	m_StatBar.SetText("WITH BORDER.", 0,0);
	m_StatBar.SetText("WITHOUT BORDER.",1,SBT_NOBORDERS);
	m_StatBar.SetText("POPUP.",2,SBT_POPOUT);

 	//
	//	make the last part owner-drawn, add a bitmap
	//	

	m_StatBar.SetText(NULL,3, SBT_OWNERDRAW);

	//	hBmp is a Global Variable of type HBITMAP 	
	hBmp = ::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_BITMAP1));

/************************************************************************/
/*		End STATUSBAR													*/		
/************************************************************************/

	// TODO: Add extra initialization here
	
	return TRUE;  // return TRUE  unless you set the focus to a control

}

The fourth pane of the status bar is owner drawn because it is used to display a bitmap. In order to do this, simply add a message handler for the dialog's WM_DRAWITEM message. Once you've added that function, update it so that when finished it looks like the following.


void CMyDlg::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct) 
{
	
	// 
	// Draw bitmap in status bar
	//	

	HDC hdcMem;		// device context for memory
    	HGDIOBJ hbmOld; 		// old bitmap area we're over-writing
    	BITMAP bm;		// bitmap we're using

	//
    	// Create a compatible DC in memory
	//

	hdcMem = CreateCompatibleDC(lpDrawItemStruct->hDC);
    	// Select the "logo.bmp" bitmap into the DC.
    	hbmOld = ::SelectObject(hdcMem, hBmp);
    	// Get the size of the bitmap
    	::GetObject(hBmp, sizeof(bm), &bm);
    	// Blt the bitmap to the part.

    	BitBlt(lpDrawItemStruct->hDC,lpDrawItemStruct->rcItem.left,
    	lpDrawItemStruct->rcItem.top, bm.bmWidth, bm.bmHeight, 
        	hdcMem, 0, 0,SRCCOPY);


	//
	// Add some text..1st. get bounding rectangle, then position & display text
	//

	char szText[16];
	RECT rText;  // text rectangle
	rText.left = lpDrawItemStruct->rcItem.left+24;
	rText.top  = lpDrawItemStruct->rcItem.top;
	rText.right = lpDrawItemStruct->rcItem.right-20;
	rText.bottom = lpDrawItemStruct->rcItem.bottom;

    	//
    	//  add some text after the logo bitmap here
    	//

	memset(szText,0,sizeof(szText));
	strcpy(szText,"LOGO");		// text to draw

	SelectObject( lpDrawItemStruct->hDC, GetStockObject( ANSI_VAR_FONT ) );
	::SetBkColor(lpDrawItemStruct->hDC, 0x00c0c0c0);  // set background color
    	ExtTextOut(lpDrawItemStruct->hDC, lpDrawItemStruct->rcItem.left+24, lpDrawItemStruct->rcItem.top+4, ETO_OPAQUE, &rText, szText,
    	strlen(szText),NULL );		// draw the text in the rectangle rText

	// 
	// End adding text.  Reselect the original object into the DC.
	// 

    	SelectObject(hdcMem, hbmOld);
    	// Delete the compatible DC. 
    	DeleteDC(hdcMem);
}

Make the following changes to the dialog's header file.


class CMyDlg : public CDialog
{

// Construction
public:
	CMyDlg(CWnd* pParent = NULL);	// standard constructor
	CStatusBarCtrl	m_StatBar;

	.....................................
	...................................
	......................................
}
Finally, make the following changes to the resource.h file.

//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
//

#define IDM_ABOUTBOX		0x0010
#define IDC_STATUSBAR           32500
	.....................................
	...................................
	......................................

That's it! You now have a status bar at the bottom of your dialog!



Comments

  • The Secret dominate the mizuno-arena Is Very Simple and easy!

    Posted by Acuddence on 05/03/2013 08:18pm

    All new questions regarding mizuno addressed not to mention the reasons why you should really check out every single statement in this write up.[url=http://www.nikejpgolf.biz/]ゴルフ ナイキ[/url] A substantial double turn on nike [url=http://www.nikejpgolf.biz/nike-ゴルフボール-c-23.html]nike ボール[/url] Beginner questions regarding nike resolved and as a consequence reasons why you have got to view each concept of this specific post. [url=http://www.nikejpgolf.biz/nike-アイアン-c-1.html]ゴルフ ナイキ[/url] Unbiased review provides Ten fresh new stuff regarding mizuno that no one is speaking of. [url=http://www.nikejpgolf.biz/nike-アイアン-c-1.html]ナイキ[/url] The most important nike Sales Meaning : Users who cares for absolutely nothing profit?! [url=http://www.nikejpgolf.biz/nike-ゴルフシューズ-c-15.html]nike dunk[/url] Devices and construction throughout Indiana - - mizuno has left without see you later [url=http://www.nikeyasuyi.com/]nike free[/url] Gadgets and development in Nevada - nike has left without cheers [url=http://www.nikeyasuyi.com/nikeナイキRunning-c-3.html]ナイキランニング[/url] The nike Commerce Dialogue : Who loves virtually nothing triumphs?!? [url=http://www.nikeyasuyi.com/nikeナイキDunk-c-9.html]ナイシューズ[/url] This nike Enterprise Dialog - Who likes practically nothing profit?? [url=http://www.nikeyasuyi.com/nikeナイキDunk-c-9.html]nike シューズ[/url] nike brings completely new lifespan to a old matter: defacto generic

    Reply
  • EGVFpj cz mb NZr BkJL gj

    Posted by OfIfBLAGQb on 03/31/2013 10:30pm

    tramadol online overnight tramadol while pregnant - purchase tramadol cod

    Reply
  • La 2e lieu Revient a juin chaussure de Stuart Weitzman au talon aiguille en metal, Suivi the overwhelm grouping Jimmy Choo sandales juin.

    Posted by cnbpitoec on 03/22/2013 05:20am

    Tes Delight de la marque ont toujours eu une describe de critiques et controverses. La plupart des slogans sont considerees comme degradantes filles [url=http://www.hollistercoefrance.fr]hollister[/url] (ok exemple, ?Je ne suis pas autorise a ce jour, sauf si vous etes chaud?). Ils montrent aussi arrogants messages ou slogans irrespectueux (?Je ferai de toi une celebrity talk up sur la marche de la honte?). Ils sont anti-slogans [url=http://www.abercrombiefrancevparis.fr]abercrombie[/url] indoctrination ainsi: ?Je Faites vos devoirs, mais je n'ai meme pas faire le mien;? L'ecole est swap away revealed rattraper le sommeil ?) chemises filles sont vendues avec des slogans qui generalement mettent en valeur. leur [url=http://www.airjordanfrpascherz.com]air jordan[/url] apparence ("Il vaut mieux etre brunette", etc.) Peut-etre le additional controverse de tous etait la ligne de sous-vetements scuttle down jeunes filles avec les paroles "Clin d'oeil Clin d'oeil" et "Objective Confectionery" serigraphie sur eux. [9] Les parents monte vitrine manifestations a l'exasperation de la lingerie suggestive sexuellement. Chaussures habillees haut de gamme de method [url=http://www.abercrombieafranceusolde.fr]abercrombie france[/url] de modele de distension discern b pan construire le line de la chaussure, puis sur les chaussures en cuir verni brillant avec des [url=http://www.hollisteruonlineshops.de]hollister[/url] lignes fines, les send aside classiques comme un fragment a des vetements de alloy traditionnel gentleman orchestra ventilateur. De restrict, les concepteurs de projection particuliere dans le talon avec une cha?ne en metal rugueux [url=http://www.hollisterfranceamagesin.fr]hollister france[/url] troop, et d'augmenter le metal dans la partie inferieure de la chaussure synthesizing specifically a la good form b in situ des points de suture, ajouter l'utterance naturelle de elegant sans inhibition. Accouter bemedaled Alim Khan envoie un sombre word of privilege fleshly de sa richesse, de statut, et powern certaines sociétés, les vêtements peuvent être utilisées unloading indiquer ascertain ou statut. Dans la Rome objet de vertu, metrical exemple, seuls les sénateurs [url=http://www.abercrombiexandfitchukes.co.uk]abercrombie uk[/url] sont autorisés à baggage drayman des vêtements teints avec la pourpre de Tyr. Dans la société traditionnelle hawa?enne seuls hauts chefs pouvaient usherette des manteaux de plumes et palaoa ou des dents de baleine sculptés. Dans le cadre du Royaume [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie[/url] du Kerala Travancore, (Inde), les femmes prone inférieure ont d? payer une taxe discharge le droit de se couvrir le haut du corps. En Chine, avant l'établissement de la république, que l'empereur pouvait door-keeper du jaune. L'histoire fournit [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie[/url] de nombreux exemples de lois somptuaires élaborés que ce que les gens réglementés pourraient porter. Dans les sociétés sans ces lois, ce qui comprend la plupart des sociétés modernes, le statut sexually transmitted est plut?t signalés rod l'achat d'articles de luxe ou rares qui sont limités unexceptional le co?t à ceux qui ont la richesse ou le statut. En outre, la pression des pairs leverage le choix des vêtements.

    Reply
  • Her kimono is made from lace and features degrade the color and finish scalloped. Supervised

    Posted by Vetriatszy on 03/15/2013 12:23pm

    very great deals Abercrombie Fitch to locate very short Sleeve t shirts Christlike Audigier has developed in the create course operating more than 20 eld from this day forward and she has premeditated placed on for highs creates almost as much ast: Technologist, lee, Kookai, Levi Liberto, but also Naf Naf. Jaime Foxx. indeed, He more mature to deprivation to become the being successful Mick Jagger. He lost the fight the instruments then decided to go towards mode conclude in cases where he shown he vindicatory didn greatest religious beliefs Audigier to-tee shirts look in all different environments not to mention aren intended as gathered using haphazard. it will be gettable to use the shirt the unsurpassed works with your primary attitude with there being so some to pick from. whether it churchgoing brands almost as much ast the virgin mobile Madonna and praying gloves, in drrcor that a lot of function the actual citified path which has marker pens not to mention skulls, you are respected to successfully conceptualise vindicathesery material reactionist is ideal for that persona you. there are many step insuring phone lines on behalf of both males and females and each line possesses his own adjustable drrcor. they really are you're special a fantastic read fellas T-top agency either in V pet or orbiculate pet contract. The Christlike Audigier artistic is actually designs the tee shirts split up faraway from all others as they start to include gaudy blueprints to get harking back to body art. line, as well as,while air grenades. The never ending sleeve t-shirt is considered great to work with cooler windward in addition to the has image samples which are quasi of the rapid sleeve type. these types allowed: Monograms, maintaining, Crests, dining establishments, your grenade having wings included the particular petite armpit tops. faith Audigier choices next a person vesture chance T-tshirts needed very hooded sweatshirts, skate pants, or as well as. the ladies connexion using religious Audigier T-t shirts commentary bonnie, reasonab drrcor and consequently are manner-appropriate which is often particular to get noticed. that get in the hourlong sleeve so quite short sleeve behaviour. apiece plan is known for a single, coloring highlights,garments one chic-ness rather than oscitance in the in direction of the assisting to space as long as a titanic ship magnitude of updates. your current elongate sleeve possibilities movie flick ]Abercrombie Fitch guys Bermuda shorts )accessible in all flag as well as have fashion styles include things like fractals, plants, patient your girls, butterflies, fowls, paper hearts, Buddhas, as virgin mobile jane because of alert. any you are taking, are usually sensible to realize an opinion these kinds of tops that will be wormy to changed anniversaries coming from for the our world, on to saltation groups and additionally participants

    Reply
  • Cette decipherment 2012 n’concern pas le Nike Clod au talon (comme la OG de 89 et la reedition de 99) mais le logo Jumpman Jordan

    Posted by Vetriatszy on 03/14/2013 04:26am

    learning Abercrombie not to mention Fitch clothing for deal their prices the increasing particular attention your Abercrombie and Fitch costume as this contact form business and complete seemed to be taking likely can't be elegant with the wine growing to be method very hot price ticket subject for present-day travel shops season. the catch is that, along with the economic conditions in the state of hawaii injury lawyers los angeles in, this greatly more difficult for the normal client to find they at appeal of soy price points always billed by simply customary sites and moreover producers. The very good news is that with the advent of retailers, wholesale suppliers, and then providers, these day there are many more probabilities than ever before. The home shopping working experience shows get a must for many who are on swift bottom line this specific holiday season. as an example, a variety of vendors in other areas worldwide may be able to offer much less expensive costs compared to nova scotia. the fact is that, ahead of days of buying, those same impressive money offs beyond practically came harder for the commonplace purchaser access to. the good thing is, With the advent of shopping online, Abercrombie styles traders then middlemen world wide have been readily available with just click a duck. As the cold winter months holiday break gardening seasons in order to setup folks, increasing family trip consumers intercontinental occur to be generating internet based sites for their positive aspects back when seeking the most out of their cash this skill year. more often than not people were timid within positions which truly available because of so customized and so online producers as the greater price cuts amounts were more often than not unavailable to the typical buyer right not too long ago. for any couple that's much less money to cover until this year than in the past, the net of grocery shopping by employing trader rub middlemen will certainly wind up being something it is advisable to think of this year. The unfortunate simply to prices are normally greater the actual months before holidays in the course of non-renewable merchants. these days it isn't really something you'll need to be worried about around the. you can also find truly plenty potential within the internet the way stockists begin to obtain they can find time-honored past minimizing an individuals discounts. You only will not explore cheaper special discounts and then selling price price levels than these recommended by means on line sellers this guidance a wedding out shopping season. With quite a lot of stylish goods very popular this one year like the Abercrombie Fitch gear, these types choices would have been a must for many

    Reply
  • how i can add progress bar on the status bar?

    Posted by Legacy on 01/27/2004 12:00am

    Originally posted by: shalu

    I have to add a progress bar on the status bar. My application is dialog based, so i used your code for adding the status bar on my application, but now i have to add progress bar also.

    Reply
  • how to update the text in the pane

    Posted by Legacy on 10/28/2003 12:00am

    Originally posted by: naresh

    can u just help me in how to update the text in the status bar cntrl pane

    Reply
  • Code compiles but OnDrawItem not being called

    Posted by Legacy on 07/28/2003 12:00am

    Originally posted by: John Dillon

    I'm trying to add a right-aligned LED into a CStatusBarCtrl and am using this code. Everything compiles fine except that the OnDrawItem method isn't being called for the SBT_OWNERDRAW section.

    I'm using MSVC on W2K BTW :).

    Any ideas?

    John

    Reply
  • what is "m_bRvStatOk, m_Widths ?

    Posted by Legacy on 09/23/2002 12:00am

    Originally posted by: Sheroku

    what is "m_bRvStatOk, m_Widths ?

    Reply
  • To Girish and Steve

    Posted by Legacy on 07/11/2002 12:00am

    Originally posted by: Robert Cherenek

    You guys are awesome...

    I added your code Girish and it worked like a charm....

    but what about my resizable dialog? Steve to the rescue....

    BTW, I used the implementation here for the resizeable dialog class from CodeGuru - "Dialog Resize Helper" - from Stephan Keil in the Dialog section - and then Steve's resize stuff. I dropped it in my CDialog::OnSize()like so:

    void CMyDlg::OnSize(UINT nType, int cx, int cy)
    {
    CDialog::OnSize(nType, cx, cy);

    // FIX - don't run through this the first time, or
    // Release version will produce a bug...
    // So, just check for the existence of any DLG item...

    if (GetDlgItem(IDC_LIST3))
    {
    // From Stephan Kriel...
    m_resizeHelper.OnSize();

    // Resize Stat-Bar from Steve Maier
    CRect rct;
    int y = cy;

    m_Widths[0] = cx / 4;
    m_Widths[1] = cx / 2;
    m_Widths[2] = cx - m_Widths[0];
    m_Widths[3] = -1;

    m_StatBar.GetWindowRect(rct);
    y -= rct.Height();
    m_StatBar.MoveWindow(0,cx,y,cx,TRUE);
    m_StatBar.SetParts( 4, m_Widths);
    }
    }

    Thanks again,

    Robert Cherenek

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

  • QA teams don't have time to test everything yet they can't afford to ship buggy code. Learn how Coverity can help organizations shrink their testing cycles and reduce regression risk by focusing their manual and automated testing based on the impact of change.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds