CIS Logo SVC Logo

   Computing & Information Systems
   Department

 

Schoology Facebook        Search CIS Site      Tutorials

Software Design Using C++



Message, Dialog, and Edit Boxes in Visual C++



Message Boxes


You can pop up a message box anytime you like just by using the AfxMessageBox function. Look up this function in Visual Studio's Help section to see in detail what it can do. For example, to show an information message in a message box with an OK button, you might use:


AfxMessageBox("File has been created", MB_OK | MB_APPLMODAL | MB_ICONINFORMATION);

The first parameter is the message to be displayed. You can use either a character array type of string or a CString. The second parameter contains various style constants combined with OR. MB_OK indicates that we want an OK button on the message box. MB_APPLMODAL says that you must respond to the message box before going on in the current window, though you can continue work on other applications in other windows. (This is the default, so this constant could be omitted.) The MB_ICONINFORMATION specifies that an icon containing the letter "i" (for "information") will be used in this message box.

Almost the same message box can be created by using AfxMessageBox with just the message parameter as shown below. The only difference is that the default MB_ICONEXCLAMATION (which is for an exclamation-point icon) will be used instead of MB_ICONINFORMATION. The OK button will be present by default.


AfxMessageBox("File has been created");

Here is a variation on the above example. The MB_ICONSTOP constant indicates that the message box will contain a red X icon, a sort of "stop sign". This is typically used for an error message. Consider this example:


CString MsgText;
MsgText = "Could not open file " + m_DataFile;   // Concatenate the 2 strings.
AfxMessageBox(MsgText, MB_OK | MB_APPLMODAL | MB_ICONSTOP);

You can also check the return value of AfxMessageBox. For example, this is used when you ask a yes/no question by using the MB_YESNO constant which puts Yes and No buttons onto the message box. We use this below along with the MB_ICONQUESTION constant which puts a question mark icon onto the message box.


CString MsgText;
MsgText = "Current choice is " + m_Choice + " -- Make a new choice?";
if (AfxMessageBox(MsgText, MB_YESNO | MB_APPLMODAL | MB_ICONQUESTION) == IDYES)
   {
   // Do whatever you want for the case when the answer is yes.
   }
else
   {
   // Do whatever you want for the case when the answer is no.
   }

Dialog Boxes in General


The AppWizard section of these web pages (under the multiple document interface links) showed how your program can bring up a dialog box of your own design. In that example the dialog box was brought up when the user clicked on a certain menu item. The basic steps in setting this up were to add a dialog resource, add a class with base class CDialog as our interface to the dialog box, and then in our code create an object of this class and call the DoModal function on it. In the particular example mentioned, this code amounted to the following, where the new class happened to be named CSizeDlg and the dialog box contained an edit box that had associated with it the variable m_FileSize.


CSizeDlg dlg;
dlg.m_FileSize = GetWindowTextLength();
dlg.DoModal();   // display the dialog box

There are also a number of common dialog boxes that are available for your use. For example, there is a font dialog box (class CFontDialog), a find and replace dialog box (class CFindReplaceDialog), a printer dialog box (class CPrintDialog), and a color dialog box (class CColorDialog), among others. In general one creates one of these dialog boxes by creating an object of the associated class, initializing any values needed by this object, calling the DoModal function on this object to display it, and then using the class member functions to get the data supplied by the user. Below we look at some typical examples of common dialog boxes. To see more about any of these common dialog boxes, look up the corresponding class under help in Visual Studio.

File Open Dialog Boxes


A file dialog box can be used either as a file open box or a file save box. Which you get is decided by using a TRUE or FALSE as the parameter to the class constructor. TRUE gives a file open dialog box. The example below shows the creation and display of a file open dialog box. The class function GetPathName is then used to get the path name of the file selected by the user. Our example places this pathname into an edit box, though what you do with the pathname is up to you.


CFileDialog m_FileDialog(TRUE);   // TRUE gives you a file open dialog box
if (m_FileDialog.DoModal() == IDOK)   // The user selected the OK button, not cancel.
   {
   m_DataFile = m_FileDialog.GetPathName();   // Assumes m_DataFile is associated with edit box
   UpdateData(FALSE);   // Put data into the edit box 
   }

File Save Dialog Boxes


The following is a similar example showing how to create a file save dialog box. The only difference is the use of FALSE as the parameter to the constructor. Once again the complete pathname was obtained and displayed in an edit box (just to keep the example simple).


CFileDialog m_FileDialog(FALSE);   // FALSE gives you a file save dialog box
if (m_FileDialog.DoModal() == IDOK)   // The user selected the OK button.
   {
   m_DataFile = m_FileDialog.GetPathName();   // Assumes m_DataFile is associated with edit box
   UpdateData(FALSE);   // Put data into the edit box
   }

Folder Selection Dialog Boxes


This one is considerably different and will not be completely explained here. The basic idea is that a BROWSEINFO structure is used to hold information needed by the SHBrowseForFolder function, which does the bulk of the work. The SHGetPathFromIDList is used on the return value from the previous function in order to get the full path to the selected folder. The example below displays this full path in an edit box, but you can do whatever you like with this data. Note that there is a lot more that can be done with the SHBrowseForFolder function. Look it up under Help in Visual Studio if you want to find out more.


BROWSEINFO bi;   // Structure to hold details about the dialog to be displayed
StringType Folder;    // Will hold just the selected folder name
StringType FullPath;  // Will hold the full pathname for the selected folder
char Title[] = "Select a folder";  // Title bar text for the dialog

// Initialization code for the BROWSEINFO struct:
bi.hwndOwner = this->m_hWnd;
bi.pszDisplayName = Folder;
bi.lpszTitle = Title;
bi.ulFlags = BIF_RETURNONLYFSDIRS;   // Used to restrict selection to folders only
bi.pidlRoot = NULL;
bi.lpfn = NULL;

// Display the dialog box and translate the full path from the return value of
// SHBrowseForFolder and store it in FullPath:
if (SHGetPathFromIDList(::SHBrowseForFolder(&bi), FullPath))
   {
   m_Dir = FullPath;   // Here we assume the m_Dir is a variable associated with an edit box
   UpdateData(FALSE);  // Put data into edit boxes (or do whatever you want to do with it)
   }
// Otherwise, if SHGetPathFromIDList failed, it was unable to get a path for a folder.

The above assumes that we have set up a type called StringType as shown below. This typedef would probably be placed in the .h file corresponding to the .cpp file for the above code.


typedef char StringType[MAX_PATH];

Edit Boxes


If you have been reading the AppWizard section of these web pages, you have already seen how to place an edit box into a dialog box. That dialog box might be the one that provides the interface for the application or an application with a single or multiple document interface might bring up the dialog box. (The former is shown on the above-mentioned page under the link for the dialog-based interface. The latter is shown under the link for the multiple document interface.)

Here is something that you might not realize is possible with an edit box: You can place multiple lines of data into an edit box. Go to properties for the edit box and turn on the multiline style as well as autoscroll, both horizontal and vertical, as well as regular horizontal and vertical scroll. Then, for example, if you want to copy all of the data from a text file into your edit box, you might use something such as the following function which has been added to the CExampleDlg class. (We assume here that the project is named Example. Replace this with the name for your project, of course.) This Display function might be called from within a function that handles a menu selection or the clicking on a certain button. (See the rest of these AppWizard web pages for more on how to do this.) Note that StringType would be set up as described above under the Folder Selection Dialog Boxes topic.


void CExampleDlg::Display(fstream & DataFile)
   {
   StringType Line;
   CString Temp;

   Temp = "";
   DataFile.getline(Line, MAX_PATH);

   while (! DataFile.fail())
      {
      Temp = Temp + Line;
      // Append a carriage return and line feed to mark the end of each line:
      Temp = Temp + '\r';
      Temp = Temp + '\n';
      DataFile.getline(Line, MAX_PATH);
      }

   m_TextBox = Temp;   // This assumes that m_TextBox is the variable associated with the edit box.
   UpdateData(FALSE);  // Put the data from m_TextBox into the associated edit box.
   }

Practice Exercise


For practice try this out, consulting the AppWizard section of these web pages as necessary when doing this: Create a simple dialog-based application that has 3 buttons on it. One button should allow the user to open a text file. The contents of the file should then be displayed in an edit box as described above. (That gives practice with the file save dialog and with multiline data in an edit box. For a shorter practice exercise, don't really open the file and put the data into an edit box. Entirely skip the edit box. Rather, just pop up a message box that reports what file was selected to be opened. No reading of the data is really necessary if you just want to try out the file save dialog box.) The next button should pretend to let the user save the contents of this edit box to a (possibly new) file. (If you wish, you can actually save the data to the file selected, but it is suggested that you keep the exercise short and just use a message box to report the file selected but not save any data to this file.) The third button should allow the user to change to a different directory. Change to this new directory and then look up the current directory by using:


StringType CurrentDir, FullPath;
_chdir(FullPath);   // change directory

_getcwd(CurrentDir, MAX_PATH);   // look up the current working directory

This assumes that StringType has been set up as explained above under the Folder Selection Dialog Boxes topic. It further assumes that you have included the direct.h header, probably by placing it in the .h file corresponding to your .cpp file. (This header is needed if you want to use the _chdir and _getcwd functions.) Next pop up a message box to report the current directory (now found in the variable CurrentDir). (Should you wish to keep the exercise shorter, just report what FullPath contains, via a message box, and skip changing directory and looking up the current directory.) If you need further help or just want to check your work, look at the following two links. Note that these two files are for Visual Studio 6.0, though the code that you need to write is the same if you use Visual Studio .NET.
  • BoxesDlg.h
    A few small additions were made at the top of this file.
  • BoxesDlg.cpp
    See the last 3 functions in this file.
From the filenames you can tell that the project was named Boxes. However, you can use any name that you like for your project. Whatever you name it, just compare your Dlg.h and Dlg.cpp files to the above ones.

Back to the main page for Software Design Using C++

Author: Br. David Carlson with contributions by Br. Isidore Minerd
Last updated: August 27, 2009
Disclaimer