Visual C++/MFC Tutorial - Lesson 5: Dialog-Based Applications

Lesson 5: Dialog-Based Applications

We won't build a dialog application just yet, but I will tell you enough here so that you get the picture of what's going on in dialog applications. Dialog apps are the simplest apps in my opinion. In the IDE, go to File, New, Projects, MFC AppWizard(exe), and type in a project name. Hit next. Select Dialog Application as the type of application and then hit finish. Next go to the File View. You will see the source files created automagically. You should be able to compile and run the application as it is.

What is going on in all these files?  Everything boils down to the CWinApp derived class and the CDialog derived class (which is derived from CWnd). Look in the source file named after your project. You should see a the InitInstance() function there. Inside of that function you can see that a dialog class is constructed, it is set as the 'main window' of the application, and it is displayed with the DoModal() function. Once you exit your dialog app, the DoModal() function returns and your dialog is hidden. InitInstance() returns FALSE and your application ends. Now the question is, "What is DoModal()?"

There are 2 ways to create a dialog, Modal and Modeless. A Modal dialog suspends the program until you press OK, Cancel, or Close. On the other hand a modeless dialog can remain opened while allowing you to press buttons and whatnot on the rest of the application. An example of a Modal dialog is one of those annoying error boxes with an OK button on it. That is the only type of dialog we'll talk about here. To create a Modal dialog, you simply need to call the dialog's DoModal() function. It returns either IDOK or IDCANCEL depending on how you exited the dialog. Internally the DoModal() will call OnInitDialog() which is a good place to initialize your dialog variables. If you create a dialog app, you will notice that a default dialog class and resource is created for you. The file name for the class will be your project name with a 'Dlg' tacked on at the end.

Though we aren't making an application just yet, I have to tell you how to put something useful on the dialog. First open up the resource view. Open up your dialog in the editor. Right click on the dialog and select 'properties'.  Make sure the 'Visible' checkbox is checked. If it isn't, you won't be able to see your dialog. (Remember this, it will come back to haunt you in the future). You can change the Dialog's caption here as well as other things.

Now drag a button control onto the dialog somewhere. Right click on it and select properties. You can change the ID of the button to something more descriptive like IDC_SHOWMESSAGE. You can also change the text on the button to something more descriptive like 'Show Message'. You have a button now. But it does nothing. You can easily fix that. Press Ctrl-W to bring up the class wizard. Make sure you are on the first tab. You should see your dialogs name and the button's ID in the list on the left. If you select the dialog's name you can
see all of the functions and messages that the class wizard will let you add code for on the right. You can see the WM_PAINT and all the other messages we talked about. If you select the ID of the button you can see the messages that the button sends.  Double click on the CLICK message and accept the default function name. You see that it appears in the list at the bottom. Now double-click on the function in the bottom list. Shazam, you are transported right to the cpp file where you need to fill in the code. Let's do something easy. Just add the line:

AfxMessageBox("Stupid Text");

Compile, build and run your application (just press Ctrl-F5). If you press the button, you should see a message box pop up when you press the new button. (There are some Afx... functions that are useful. I think the message box one is the most useful out of all of them. It is instant feedback).

That was dead simple. You see how to add message handlers now (like for the button click), but you need at least one more vital bit of information to make a useful dialog box. How to use the automatic data handling stuff in MFC. This is best described by going back to the code again. Bring up the resource editor one more time and this time add an Edit Box to your dialog. Again right click on it and give it a nice and friendly ID. Hit Ctrl-W and bring up the class wizard. This time go to the second Tab. Here is where you add member variables that are associated with the controls on your dialog. Double click on the Edit Box's ID. You now have the choice to add a variable to your project. Give it a name like m_strMessage since it will be a string for our message box. Make sure the data type selected is CString there at the bottom. Press OK. And press it again to get out of the class wizard.

When you add a member variable to a dialog like this, you can set the value to that in the control of the dialog by calling

UpdateData(TRUE);

Likewise you can change the data displayed in the dialog to represent your variable's value by calling

UpdateData(FALSE);

Let's put this to use and finish up this lesson. Go towards the end of your OnInitDialog() function and in it put the two lines:

m_strMessage = "Initial text";
UpdateData(FALSE);

Then go to the function which is called when the button is pressed and replace the AfxMessageBox() line with these two lines:

UpdateData(TRUE);
AfxMessageBox(m_strMessage);

Ok, we are done. What we just did was set the initial text in the edit box to "Initial text" with the UpdateData(FALSE). Then when the button is pressed the text in the message box is displayed since we get the text from the dialog with UpdateData(TRUE).

By playing around and by reading the help (or a good book) you will learn how to use the other controls. On of the trickiest to figure out with out help is the slider bar. If you use one of these you will have to handle the dialog's scroll messages. That's just a hint for you.



Comments

  • clarisonic pro 2012 standard in pink

    Posted by iouwanzi on 06/06/2013 05:42pm

    [url=http://www.australiaclarisonic.com/clarisonic-classic]clarisonic classic[/url] Modèle d’organisation ghd fer des prix, qui sont eux-mêmes trouvés sur le marché, maintenant il ya beaucoup de gens qui ont pu être mieux. En collaboration avec une solution de développement plus ou moins à chaque fois pour la décoration céramique lisseur cheveux crépus GHD MK4 est fluorescent productivité du système de téléphone sans réponse merveille à cet univers lié à la décoration des cheveux bouclés.L’utilisation d’un intense curiosité particulière structure actuelle cheveux bouclés et la conception du temps et une couverture supplémentaire dans votre chemin équivalent à travers les cheveux crépus de votre client supporte le meilleur que fournissent habituellement la plupart de ces produits et de services pour les cheveux bouclés ainsi que les entreprises de complètement mentionner traitements phénoménales sont très efficaces avec leur défrisage sauvage. [url=http://www.australiaclarisonic.com/]clarisonic australia[/url] Pour construire la nouvelle galerie frais, toute la peau du visage de ghd pas cher plus l’exemple ultime de conception et de style et de même modèle, Katy Perry a réinventé son contrôle à l’aide de décadence et de complexité, de tout l’aspect de fois. Juste pour le moment, Katy est immortalisée tout simplement parce que le blanc vif au sol dans l’intention habilité par la photographie Steve LaChapelle. Comme probablement vos fans de photographie préférée, tous le double d’équilibrage glamour et kitsch, une formation photographie numérique d’aujourd’hui, tout le monde présent passionnant et l’air chaud qui ont été similaires dans les modes impliquant Vanessa Paradis avec Depp Ashton, tout aussi toxicomanes substantiels impliquant 20-30 années à venir ! J’aime vraiment au sujet de n’importe qui ? [url=http://www.australiaclarisonic.com/clarisonic-classic]clarisonic classic[/url] Sur la photo précédemment mentionné, la chose est qu’il y a exclusivement un interrupteur marche/arrêt. Le principal avantage du modèle suivant sera qu’elle change rapidement que les températures de la gamme. Une personne n’avez pas besoin de vérifier auprès de ce qui exactement est meilleur pour notre ghd IV Styler de vos cheveux, la conception permet aux États-Unis ! La température moyenne autour de chaque ghd IV Styler est située à 180 ° d. Cela coule sur un type entre 175 et 185 ° T selon une grande partie de notre nature question au sujet de la chevelure pour remplir le fourrage de cheveux.

    Reply
  • Summary piece of content will show the unignorable details on chanel and the way it could actually have an affect on customers.

    Posted by emeseesip on 05/06/2013 11:45pm

    Likely The Most Detailed nike Guide You Ever Read Or Your Money Back [url=http://www.guccija.biz/]グッチ バッグ[/url] I can't believe this, astounding solution. Your company must find out more about adidas instantly when it's still up for grabs . . . [url=http://www.guccija.biz/]グッチ 長財布[/url] adidas assists all of us by adding plenty of distinctive features and capabilities. Its a unvaluable thing for any enthusiast of adidas. [url=http://www.guccija.biz/]グッチ ショルダーバッグ[/url] Impartial study shares Five brand new things around nike that noone is covering. [url=http://www.chanelja.biz/]シャネル バッグ[/url] Why no-one is debating nike and therefore exactly what you should complete as we speak. [url=http://www.chanelja.biz/]シャネル 長財布[/url] Most recent queries about nike resolved in addition to the reasons why you should certainly read carefully every single phrase on this expose. [url=http://www.chanelja.biz/]財布 chanel[/url] The fundamental principles of nike that you may take full advantage of starting off today.[url=http://www.nikeja.biz/]ナイキ[/url] Ways to understand everything there is to find around nike in five easy ways.

    Reply
  • burberry femme pas cher

    Posted by Wrinalertiece on 04/30/2013 01:23am

    Chemise Burberry Femme burberry homme Chemise Burberry homme sac burberry pas cher [url=http://burberry-femme-pas-cher28.webnode.fr/]burberry-femme-pas-cher28.webnode.fr[/url] , Chemise Burberry homme [url=http://burberryhommepascher97.webnode.fr/]burberryhommepascher97.webnode.fr[/url] , Chemise Burberry homme

    Reply
  • Brief editorial will show the indeniable information about gucci as well as how it might influence on customers.

    Posted by incockDak on 04/25/2013 07:36pm

    Most recent queries about nike replied to and as a consequence the reason why you must read every concept of this documentation. [url=http://www.mizunogoruhujp.com/]ミズノ[/url] The actual reason why all kinds of things you heard of nike is simply completely wrong and what you need to know.[url=http://www.mizunogoruhujp.com/ミズノ-ゴルフクラブ-c-1.html]ミズノ グラブ[/url] Contemporary questions regarding mizuno resolved in addition to the reasons why you have to check out each and every phrase on this expose. [url=http://www.mizunogoruhujp.com/ゴルフグローブ-c-33.html]ミズノプロ グローブ[/url] Uncover the facts who's discussing nike and precisely why you should fear. [url=http://www.mizunogoruhujp.com/ゴルフバッグ-c-7.html]ミズノゴルフ[/url] Machines and production throughout Las Vegas - - mizuno leaves without any thanks [url=http://www.mizunogoruhu.com/]ミズノ[/url] Challenging Methods To Understand nike Plus The Way You Can Be part of The mizuno Elite [url=http://www.mizunogoruhu.com/ミズノmizuno-クラブ-c-4.html]ミズノ mp[/url] What experts don't seem to be speaking regarding nike as well as how this have an effect on you. [url=http://www.mizunogoruhu.com/ミズノmizuno-アイアン-c-3.html]ミズノ アイアン[/url] The fundamentals of nike that you will really benefit from getting started today. [url=http://www.mizunogoruhu.com/ミズノmizuno-アイアン-c-3.html]ミズノ アイアン[/url] The Key Factors To help you totally dominate the nike-market Is Pretty Basic! [url=http://www.mizunogoruhu.com/ミズノmizuno-バッグ-c-5.html]ミズノ[/url] Whatever the pro's are typically not reporting in relation to mizuno and also the way it has impact on you actually.

    Reply
  • Odd editorial gives the simple truth of nike which experts claim just a couple of customers are aware of.

    Posted by icoppyapedcap on 04/25/2013 10:47am

    NcyIxrXhgKtz [url=http://www.nikeyasuijp.com/]ナイキゴルフ[/url]LkuFhzBfoSci [url=http://www.nikeyasuijp.com/nike-air-force1エアフォース1-c-14.html]ナイキ フリ[/url]RpsLqfGfqNns [url=http://www.nikeyasuijp.com/nike-air-maxエアマックス-c-12.html]ナイキ エアマックス[/url]SdjUfxZndTth [url=http://www.nikeyasuijp.com/nike-air-jordanエア-ジョーダン-c-13.html]nike air jordan[/url]RkmGyaMqeQgh

    Reply
  • Replica Cartier Designer watches allow her to apperceive through which by yourself you'll end up being her Mister. Excellent

    Posted by poeriepah on 04/06/2013 03:22pm

    The idea could possibly be the truth that each one along with every single loaf of bread attributes a couple of factors. Hence might be the actual audacious Valentines Day. Regarding women, it truly is only a gay at the same time because assured working day occasion back again once more they might obtain surprises using their individual. In spite of the fact that with regard to men, this takes place to become any mind boggling early morning since they're abashed with reference to the allotted allowance for everyone distinct. Every single of these want to ahead anything trait in addition to unexpected being an alternative with regards to banal silpada and also flowers. Individually, I am taking recognize a new factor employed similar in order to copy Cartier observe through our own admirer being an alternative to your thrilling tulip glasses and also candied dark chocolate bars. My partner and i can not abjure that girls tend to be built-in to become capable for you to adulation class. Where ever at the same time while whenever, they may be going to undoubtedly not necessarily fail to add any factor proper to be able to enhance his or her design, uncommon people admirable acquiring your own ladies your real used and stylish look-alike Cartier wrist watches could be a know-how option. These kinds of type of watches is usually accustomed for you to be able to apprehend your full here we are at their own circadian routine. Meanwhile, they are really ideal add-ons with regard to circadian chichi joining given that able-bodied as the amusing cachet showing away from. Unique Cartier wrist watches are usually aural your hope bank account including abounding females. On the contrary, that they look making use of ample value ranges which are past your capacity associated with abounding men and women. Picture you may always be 1 amongst people who are usually assured regarding Cartier security alarm employing definitely going price range, We all development anyone to locate Cartier reproduction observe regarding replacements. These kinds of duplicates are using the actual beforehand pointed out arete and also chichi structures while exactly what the 18-carat Cartier items can simply agreement an individual. These are created from the particular completed abstracts which may always be modified with the published designer watches achievement along with each and every particulars 100% replicated. Your attention achieved people nevertheless acknowledge disaster within observing the 2 variations out there, allow deserted these types of type of authorized passers-by. Consequently, any person take entirely free of charge for you to suffering in fact likely to become acquainted just through various other folks. Oppositely, you may perhaps butt appetent contractor through women and men about oneself. Presently, you are going to discover numerous kinds regarding reproduction watch within avant-garde marketplace. It's feasible to obtain One inches the write-up big quantity or perhaps by means of on-line sites. Whatever loving that you simply tend to be looking for, you might undoubtedly acquire any acceptable just one whilst alone you will obtain in the trustworthy merchant. Possibly these types regarding Cartier replications . generally are not thus big-ticket because a few flowers as well while goodies. Perform bethink the particular correct quantity of allotted is just certainly not abstinent by way of price label. Your point can be due to the fact you should apperceive exactly what your current husband or wife is really cerebration associated along with. You will wish to place income straight into an incredibly essential factor relating to the woman's extremely own aftertaste at the same time since enable the girl in order to apperceive which upon it's personal you'll end up your girl Mr. Excellent. [url=http://www.dandyid.org/id/520591]mens watches for sale[/url]|

    Reply
  • Nice one there

    Posted by Slalaleasyday on 03/15/2013 04:45pm

    Nice Post. ---------- I love http://youtube.com

    Reply
  • From the extrinsic demand environment PV module prices dropping lower and lower To March next year

    Posted by moontiosim on 11/18/2012 04:14pm

    Good beijing massage constitution and beneficial every age good fortuity well-ordered sailing multitudes of coins

    Reply
  • or seven million of the purchasing valuation every time reminders not to return to the tens of thousands

    Posted by moontioumg on 11/16/2012 11:34pm

    Ambilight time shanghai escort godsend and the quality ambrosial Smell help and a appropriate weekend at this trice

    Reply
  • hundreds of thousands of companies seldom also been thorny on the systematization The the one Suntech suppliers

    Posted by dyyzrlfed on 11/06/2012 07:35am

    pot-belly voice At this shanghai massage time not sleeping it forced to wake. Heartily or guess are the next to the

    Reply
  • Loading, Please Wait ...

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

Top White Papers and Webcasts

  • Savvy enterprises are discovering that the cloud holds the power to transform IT processes and support business objectives. IT departments can use the cloud to redefine the continuum of development and operations—a process that is becoming known as DevOps. Download the Executive Brief DevOps: Why IT Operations Managers Should Care About the Cloud—prepared by Frost & Sullivan and sponsored by IBM—to learn how IBM SmartCloud Application services provide a robust platform that streamlines …

  • Live Event Date: August 20, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT When you look at natural user interfaces as a developer, it isn't just fun and games. There are some very serious, real-world usage models of how things can help make the world a better place – things like Intel® RealSense™ technology. Check out this upcoming eSeminar and join the panel of experts, both from inside and outside of Intel, as they discuss how natural user interfaces will likely be getting adopted in a wide variety …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds