You are on page 1of 17

Creating Dialog Based Applications with MFC 7

By Jason Pursell, University of Washington, Bothell (2000-2003) jpursell@u.washington.edu (Used by per ission obtained 3!"#!0$ and adapted by %i&'i () *llan)

Introduction
Windows programming involves using a graphical user interface with buttons, text areas, radio buttons, etc. Thus, instead of having your input come from a file and your output go to a file or to the screen, you can have various kinds of graphical input and output. In a Windows program, the control is very different. Instead of having a main program which controls the actions, the control is given to the user. Thus, whenever a button is pressed or a value entered, the program is expected to respond appropriately. This style of control is termed event driven, and can be very different to manage. Visual !! helps us to arrange the graphical resources "buttons, text areas, etc.# on the screen and also aids us in mapping user actions "pressing a button, changing a text area# into functions that the program performs. Thus, if we wanted to create a button which caused a specific action, we would define a method "associated with the button# such as $n%utton&ress in which we would specify what to do when the button was pressed. 'ssume this action causes something to be printed in a text area. In addition, we would need to know what we should do to change the value that the program displays in the text area. This is done by associating the text area with a variable of some type. Then, we change the variable and ask that the system update the associated text area on the string. In Windows programming, we are dealing with old style , so some of the data types are limited. In this tutorial, we are also letting Visual !! control everything. We even add global variables using button clicks. This is not necessary, but is an interesting way to program. (ote how the integrated environment tries to save you work.
+his tutorial de onstrates ho, to &reate a simple dialog based appli&ation ,ith -./ # and %isual 0tudio )12+) Note: +his tutorial is based on another one fro /odePro3e&t)&o , A Beginners Guide to Dialog Based Applications Part One, by 4r) *sad *lti ee y

The Visual Studio .N T ID


While the e5a&t vie, of the 642 ay vary a bit, the parts are all the sa e) The !ost "rustrating thing "or !e was not to ha#e the options or #iews indicated in the handout. The wa$s o" !anipulating the #iew are shown in %old. This section gi#es an o#er#iew o" the #arious windows. The actual instructions "or %uilding a pro&ect are in the ne't section.

3,4,5 2

Figure (. 0o e parts of the 642 that are ne, and!or i proved)

Solution

'plorer

Class View

)esource View

ID

Co!ponent

(. Tool%o' *. Dialog ditor +MFC,

Description 7 4isplays a variety of ite s for use in %isual 0tudio pro3e&ts su&h as &ontrols, &o ponents, and &ode!te5t frag ents) 7 +his is ,here you &reate or edit dialog bo5 resour&es) Be,are 7 this is not Windo,s .or s8 7 Provides you ,ith an organi9ed vie, of your pro3e&ts and their files as ,ell as ready a&&ess to the &o ands that pertain to the )

-. Solution

'plorer

.. Class View

/. )esource View

5. 6roperties 7indow
Ta%le (. 642 &o ponents)

7 4isplays a progra ati& vie, of sy bols in your &ode, for e5a ple, na espa&es, &lasses, ethods, and fun&tions) Variables you have added are visible at the bottom of this view under CProjectNameDlg 7 4isplays the resour&e files in&luded in your pro3e&ts and allows $ou to get %ac0 to the Dialog ditor %$ dou%le clic0ing on IDD1ProjectName1DIA234 under the Dialog la%el. 8 Use this ,indo, to vie, and &hange the design-ti e properties and events of sele&ted ob3e&ts that are lo&ated in editors and designers)

+he lo&ation of the ea&h of the vie,s (or ,indo,s) is totally dependent upon the profile you are using) +he profile &an be set fro the Start Page under My Profile) +he Start Page usually sho,s ,hen you start %isual 0tudio )12+) 6 li'e the profile :0tudent Windo, ;ayout<) +he 0olution 25plorer, /lass %ie,, and =esour&e %ie, >3,$,?@ are displayed in the sa e spa&e) Switching %etween the #iews is done %$ clic0ing on the ta%s %elow the! +as shown in the picture,. I" the )esource View 9/: is not present in the ta%s; $ou can also get these #iews to appear %$ clic0ing on icons that are part o" $our ID . To see which #iews are associated with each icon; hold the !ouse o#er each icon until the tool tips displa$. The diagra! %elow shows the icons associated with each #iew.

+he properties ,indo, is sho,n in (Figure *)) +he first t,o on the left 3ust deter ine ho, the ite s are displayed in the list) +he ne5t three deter ine ,hat is displayedA Properties, Control Events, Messages, or Overrides (in that order)) Control Events, Messages, and Overrides are only available ,hen &ertain things are sele&ted) .or e5a ple, Figure * is ,hat is available ,hen /4ialog"4lg is sele&ted in the Class View (as in the pi&ture of the Class View at the top of the page)B ho,ever, the Overrides i&on is only sho,n ,hen a &lass is sele&ted)

Categori=e 6roperties Show 3#errides Alpha%eti=e 6roperties Show Messages

Show Control #ents Show 6roperties

Figure *. Buttons of the properties ,indo,)

)how properties by group

Creating a New 6ro&ect +and Solution,


+o &reate a ne, pro3e&t, &hoose File New 6ro&ect on the ain enu) +he New 0ele&t Visual C<< 6ro&ects and MFC Application)

)how properties alphabetically Project dialog ,ill open)

Figure -. 1e, Pro3e&t dialog)

Write Dialog( in the pro3e&t Name field) Press CD) +his ,ill &reate files sho,n in Figure ..

)sln 7 0olution .ile )n&b 7 6ntellisense 4atabase )sou 7 0olution User Cptions

Figure .. .iles &reated inside the 4ialog" solution folder ,hen the Create directory for Solution &he&'bo5 is sele&ted)

+here is also a file =ead-e)t5t ,hi&h is &reated in your dire&tory) 6t e5plains all of the files that are &reated by %isual /EE) Cn the enu, &hoose Application T$pe (&ir&led in red in Figure /))

Figure /. Page one of the ,i9ard)

Figure 5. *ppli&ation +ype page of the ,i9ard)

/hoose the options that are &ir&led in red in Figure 5)/li&' the Finish button)

*se the lassView tab to see the actual files that have been created. The file +ialog,+lg.cpp references the 'bout+lg, +ialog,'pp and the +ialog,+lg class declarations.

The visual elements of a pro-ect are called resources. .or example, icons, dialog boxes, buttons, and menus are resources. The wi/ard has created folders of resources. lick on the 0esource tab to see the folders.

Designing the Dialog


Note: I" the Dialog ditor is not showing; open the )esource View and e'pand the Dialogs "older and dou%le>clic0 IDD_DIALOG1_DIALOG.

In this example, we are going to create a window like that shown in .igure ,1 which will help us input names.

1. /li&' the title bar to sele&t the 4ialog itself) 2. 0ele&tion (andle) +his &an be dragged to &hange the si9e of the dialog) +he ,idth and height are indi&ated in are belo, &ir&led in blue)

HINT: 6nvestigate the blue line after the tutorial) +ry to figure out ,hat it is used for) 6t &an be useful)

Figure 7. +he 4ialog 2ditor in a&tion)

/li&' on the te5t TO O! Place dialog controls "ere, then press Delete) 1e5t, as in Figure 7 above, sele&t the dialog by &li&'ing on the edge of the title bar) +he dialog ,ill no, have si9ing handles on its sides and &orners) +hese are used to resi9e the dialog) +he ,idth and height of the dialog is indi&ated at the botto -right of the 642 and is &ir&led in blue in the diagra above) +hese si9e and ,idths also sho, the si9e of &ontrols you ,ill add later) 0in&e ,e donFt need the Cancel button in our appli&ation, sele&t it by left-&li&'ing it on&e) +he button is sele&ted ,hen si9ing handles surround it) Press Delete) 1e5t ,e need to &hange so e of the properties of the 3? button) 0ele&t the 3? button by left-&li&'ing it on&e) Figure @ sho,s ho, the Properties ,indo, refle&ts the properties of the button ,hen it is sele&ted)

Note: 4epending on your &hoi&e of 642 setup, the properties ,indo, ight be on the left or right) 6f it is not sho,ing, then &hoose View 6roperties 7indow or press F. on the 'eyboard)

Figure @. Properties of the CD button)

/hange the Caption of the button by typing Close in the value field of the /aption property (as sho,n in Figure A))

Type in here!

Figure A. /hanging the /aption property of the button)

1o, the button on the dialog reads :/lose<)

1e5t ,e ,ill add so e additional &o ponents (ter ed &ontrols) to &reate a GU6 as sho,n if Figure (B. We ,ant to &reate a ,ay for the user to add na es to a list of na es) +he user ,ill spe&ify a personFs title, first na e, and last na e) 2a&h of these ite s ,ill appear in a different bo5)

+rag the icon for each component onto the dialog window. This is done by clicking on the icon for a button and holding the mouse down while moving the mouse. (ow resi/e the component. 2ou will resi/e the button by placing the cursor over the corner of the component until it changes into a two headed diagonal arrow. 3old the cursor down while sliding the mouse. The component should change si/e.

Cint: When a &ontrol on the for is sele&ted, you &an :nudge< it by pressing one of the arro, 'eys on the 'eyboard) +his provides finer ad3ust ents of the &ontrolFs pla&e ent than is possible by using the ouse) ;i'e,ise, you &an gro, or shrin' your &ontrol by holding do,n the Shi"t 'ey and then pressing one of the arro, 'eys) +his is an alternative to using the resi9ing handles) +ry these te&hniHues as you &reate this dialog)

Use Ta%le * as a guide to add &ontrols to the dialog) (While there is nothing agi& about the na es ,e have used, the rest of the tutorial ,ill be u&h easier to use if you type the in e5a&tly as sho,n)) *s you add ea&h &ontrol to the dialog, &hange its properties to the values sho,n in the table) We ,ant to build a dialog si ilar to Figure (B) Please see Figure (( for an e5a ple of the property settings for the &o bo-bo5) Control 0tati& 0tati& 0tati& Button 2dit 2dit /o bo Bo5 6ropert$ /aption /aption /aption 64 /aption 64 64 64 4ata +ype 64 Value +itle .irst 1a e ;ast 1a e 64/I*44 *dd 64/I.6=0+1*-2 64/I;*0+1*-2 64/I+6+;2 -r)B-rs)B-issB-s)B4r) 4rop ;ist 64/I1*-2;60+

;ist Bo5

Ta%le *. +he &ontrols and their properties that ,e ,ant to &hange)

Figure (B. 25a ple layout of the 4ialog" dialog)

(ere is an e5a ple of the properties of the &o bo-bo5 &ontrol that ,e added) +he properties ,e ,ill &hange are highlighted in red)

(otice, these values are not visible in the dialog editor, but only show up when you execute.

Figure ((. +he properties of the 64/I+6+;2 &o bo bo5 &ontrol)

1e5t, ,e need to spe&ify the length of the &o bo-bo5 drop do,n list) Position the ouse over the drop-do,n arro, of the &o bo-bo5 and left-&li&' on&e) Use the blue resi9ing handle to ad3ust the length, si ilar to Figure (*) /li&' the drop do,n arro, on the &o bo-bo5 again to toggle ba&' to the nor al &ontrol resi9ing ode)

If you need a multi4line edit box, you need to make sure that you re5uest that your edit box be treated as multi4line. 0esi/e the edit box to be considerably larger. *nder the &roperties window select 6ultiline, 3ori/ontal )croll, 'uto 3)croll, Vertical scroll, 'uto V)croll, and Want return. When you write to this edit box, instead of -ust using \n you must use \r\n. If you only use \n or forget to specify the edit box as multi4line, you will get a strange symbol instead of a newline on your screen.

") ;eft-&li&' to toggle the si9ing ode) 2) *d3usts length of sele&ted drop bo5

Figure (*. 0pe&ifying the length of the open /o bo-bo5 list)

Assigning Me!%er Varia%les to Controls


;etFs add so e variables to tie the GU6 to the data) -a'e sure that the 4ialog 2ditor is open and a&tive) 6n order to a&&ess the #dd Mem$er Varia$le %i&ard, &hoose 6ro&ect Add Varia%le fro the ain enu) Jou &an also right &li&' any,here in the 4ialog 2ditor and &hoose Add Varia%le fro the pop-up enu) +his is fine for regular old variables, but for variables that represent &ontrols, you should right-&li&' on the &ontrol) +his ,ay the #dd Mem$er Varia$le %i&ard ,ill start, but it ,ill load up ,ith the fields already filled ,ith the default settings for that &ontrol)

Figure (-. =ight-&li&'

enu)

We ,ill ,or' ,ith the First Na!e 2dit &ontrol first) 6n the 4ialog 2ditor, right-&li&' the First Na!e 2dit &ontrol) .ro &hoose #dd Varia$le. the pop-up enu,

*s in Figure (., a'e sure the follo,ing settings are present before pressing the Finish buttonA Control varia$le checked, Control ' to IDC1FI)STNAM , #ccess to pri#ate, Category to Value; Varia$le type to CString, Control type to DIT, and Varia$le name to !1strFirstNa!e. * ,ord of e5planation on &ategoryA Value means

that it will handle data values, while ontrol means that you can control some feature of the component itself like disabling it or setting the si/e.

hange this one first

Figure (.. +he *dd -e ber %ariable Wi9ard for the .irst 1a e edit &ontrol)

Use ta%le - as a guide to enter the other variables) 6f the syste the values you ,ant, try &hanging another field first)

,onFt let you enter

)e!e!%erA =ight-&li&' on the &ontrol to add a variable) +here are other ,ays, but this is the easiest for you, be&ause it :pre-fills< so e of the fields)

NoteA 64/I1*-2;60+ ,ill have t,o variables asso&iated ,ith it) Cne is a /0tring and the other is a /;istbo5) * ;istBo5 is 3ust a &olle&tion of ite s that the user &an sele&t fro (using the ouse))

Control ID 64/I;*0+1*-2 64/I+6+;2 64/I1*-2;60+ 64/I1*-2;60+

Access private private private Private

Varia%le t$pe /0tring /0tring /0tring /;istbo5

Varia%le Na!e Istr;ast1a e Istr+itle Istr.ull1a e I1a e;ist

Categor$ %alue %alue %alue /ontrol

Control t$pe 246+ /C-BCBCK ;60+BCK ;60+BCK

Control #aria%le yes yes Jes yes

Ta%le -. +he re aining variables that need to be added via the *dd %ariable Wi9ard

's you add various controls, you may find yourself inside the code view, rather than at the +ialog 7ditor view. To get back to the +ialog 7ditor view, sele&t the tab labeled 4ialog")r&
(as &ir&led belo,))

If you create the variables incorrectly, one way to fix them is to -ust modify the code that the system created for you. "In other words, in +ialog,+lg.cpp and +ialog,+lg.h, find the declarations8uses and change them.# )tring is an old style string. 2ou can convert between strings and )trings easily. 2ou can -ust assign a string to a )tring via assignment, but to create a )tring from a string, you must use the converstion method c9str"#. Thus, if s is a string and cs is a )tring, cs : s.c9str"# is legal.

Adding Message Candlers "or the Controls


*n event handler is a ,ay to asso&iate a fun&tion &all ,ith an event su&h as &li&'ing on a button) +here is ore than one ,ay to add an event handler) 6 ,ill sho, a &ouple of ,ays here) 2a&h has pros and &ons) Note: =ead over %oth ethods first and then de&ide ,hi&h one you ,ant to use)

Method 3ne =ight-&li&' on the &ontrol that you are interested in (the *dd button in this &ase), then &hoose #dd Event (andler fro the pop-up enu (see Figure (/)) +his ,ill bring up the Event (andler %i&ard) +here you &an fill in the infor ation) /li&' the Add and dit button ,hen done) +his ,ill ta'e you to the ne,ly added ,here you &an begin adding your o,n &ode) ethod

Figure (/. *&&essing the 2vent (andler Wi9ard fro

right-&li&'ing on &ontrols)

Method Two +he se&ond ethod is done through the Properties ,indo, and is Huite &onvenient) .irst, left-&li&' on a &ontrol to sele&t it) +he Properties ,indo, ,ill &hange to represent the &ontrol) /li&' the Control Events button (using the lightning i&on at the top)) 1e5t, &li&' on the BN1C2IC? D &ontrol event) 6f you &li&' the do,n arro,, you ,ill see Figure (5) We ,ant to use our o,n na e, so instead, 3ust type in the field as in Figure (7) *s soon as you press nter, the ain ,indo, ,ill &hange to &ode vie, and the &ursor ,ill be positioned in the ne,ly &reated ethod ,aiting for you to add so e of your o,n &ode) +he &ode that you ,ill add is on the ne5t page)

4onFt &hoose this unless you ,ant the fun&tion to have the default na e)

Figure (5. +he default event handler fun&tion na e provided by -./)

We ,ant to use our o,n na e, so 3ust left-&li&' on&e in here and typeA On#dd +hen press nter.

Figure (7. *&&essing the *dd 2vent (andler through the Properties ,indo,)

1o, that youFve read through both Add button)

ethods, follo, one to add an event handler for the

*dd the follo,ing &ode to the On#dd fun&tionA


void CDialog1Dlg::OnAdd() { // TODO: Add your control notification handler code here CString strTitle; int nIndex; UpdateData(); // DDX - Transfer data from the controls to variables

//get the currently selected text nIndex !etDlgIte"Text(IDC#TIT$%& strTitle); "#str'(ll)a"e strTitle * + + * "#str'irst)a"e * + + * "#str$ast)a"e; "#)a"e$ist,AddString("#str'(ll)a"e); UpdateData('A$S%); // DDX - Transfer data from variables to controls

Building and )unning the 6rogra!


+o run, 3ust press CT)2<F/ or De%ug Start 7ithout De%ugging) /hoose :Jes< ,hen as'ed to rebuild the files) Cint Using Start 7ithout De%ugging is u&h faster than 0tarting (,ith debugging)) +his is espe&ially true ,hen &o piling /L or %B)12+ progra s in %isual 0tudio )12+) +he debugger is very po,erful, though, so ,hen you need it, 3ust &hoose Start (or F/))

Figure (@. 4ebug

enu)

6f everything ,as done &orre&tly, you should be able to type values into the fields and press the *dd button to &opy the values into the 1a e list)

+he Wido,s KP the e settings are in effe&t, be&ause -./ # auto ati&ally &reates a manifest file as part of the resour&es) (T"is can $e disa$led) 6t is only available on Windo,s KP or better)

Figure (A. 25a ple appli&ation)

Co!%ining with other classes


2ou can also add additional classes for the program to use. To do this, create a .h and a .cpp file as you normally would and add them to the pro-ect. $ne additional step is to add the line; <include =stdafx.h= at the top of your .cpp file. This will include the stdafx.h file which contains the inclusion of standard header files that are used fre5uently but not often changed. (ow you can use this class in the pro-ect as you normally would.

)esources
.or ore help on getting started ,ith %isual 0tudio )12+ and!or -./ # please see follo,ingA
- www.msdn.microsoft.com - www.msdn.microsoft.com/library/default.asp?url=/vs/techinfo/Default.asp - www.codeproject.com - www.gotdotnet.com

+he -041 library that &o es ,ith %0 )12+ also has gigabytes of help on ho, to use the 642 and -./ #) 6t also &ontains ,hitepapers on &o patibility issues bet,een -./ M and # and general standards &onfor an&e ,ith :0tandard /EE< (,hi&h is u&h i proved))

You might also like