Home > Articles > Programming > Windows Programming

Using Common Dialogs in C++.NET

The Windows operating system provides a number of pre-existing dialog boxes. This article shows you how to create and use these system (or common) dialogs with a combination of a variable declaration of a C++ class and a series of interactions with the class instance.
This article is excerpted from Chapter 6, "Adding Dialog Boxes to Your Application for User Feedback," from Sams Teach Yourself Visual C++ .NET in 21 Days, by Davis Chapman (Sams Publishing; ISBN 0672321971).
This chapter is from the book

Using common dialogs isn't quite as simple and easy as using the MessageBox function, but it's still quite easy. The Microsoft Foundation Classes (MFC) provides several C++ classes for common Windows dialogs. These classes are listed in Table 6.6.

Table 6.6 Common Dialog Classes

Class

Dialog Type

CFileDialog

File selection

CFontDialog

Font selection

CColorDialog

Color selection

CPageSetupDialog

Page setup for printing

CPrintDialog

Printing

CFindReplaceDialog

Find and Replace


The common dialogs encapsulated in these classes are the standard dialogs that you use every day in most Windows applications to open and save files, configure printing options, print, perform find and replace on documents, and so on. In addition to these choices, a series of OLE common dialog classes provide several common functions to OLE or ActiveX components and applications.

All these dialogs are used in the same manner, although the individual properties and class functions vary according to the dialog functionality. To use one of these dialogs, follow these steps:

  1. Declare a variable of the class type.

  2. Set any properties that need to be configured before displaying the dialog to users.

  3. Call the DoModal method of the class to display the dialog to users.

  4. Capture the return value of the DoModal method to determine whether the users clicked OK or Cancel.

  5. If users click OK, read any properties that they may have set when using the dialog.

To better understand how this works, add the CFileDialog class to your application. To do this, add a function to the clicked message on the File Open button. Edit this function, adding the code in Listing 6.2.

Listing 6.2 The OnBnClickedBfileopen Function

void CDialogsDlg::OnBnClickedBfileopen()
{
  // TODO: Add your control notification handler code here
[ic:Input]CFileDialog ldFile(TRUE);

// Show the File Open dialog and capture the result
  if (ldFile.DoModal() == IDOK)
  {
    // Get the file name selected
    m_strResults = ldFile.GetFileName();
    // Update the dialog
    UpdateData(FALSE);
  }
}

This code first declares an instance of the CFileDialog class. This instance is passed TRUE as an argument to the class constructor, which tells the class that it's a File Open dialog. If you pass it FALSE, it displays as a File Save dialog. There's no real functional difference between these two, only a visual difference. You can pass many more arguments to the constructor, specifying the file extensions to show, the default starting file and location, and filters to use when displaying the files. All the rest of these constructor arguments have default values, so you don't have to supply any of them.

After creating the instance of the File Open dialog, the code in Listing 6.2 calls its DoModal function. This is a member function of the CDialog ancestor class, and it's available in all dialogs. The DoModal function displays the File Open dialog to users (see Figure 6.4). The DoModal function's return value is examined to determine which button the users clicked. If the users click the Open button, the IDOK value is returned, as with the MessageBox function. This is how you can determine whether your application needs to take any action on what users selected with the dialog box.

Figure 6.4. The File Open dialog.

NOTE

Depending on which operating system you are using, the File Open dialog may look different from the one shown in Figure 6.4. All screenshots in this book were taken on Windows 2000. If you are using a different OS, the standard dialogs that appear will be the standard dialogs available in that version of Windows.

To display the name of the selected file, set the m_strResults variable to the return value from the GetFileName method of the CFileDialog class. This method returns only the filename without the directory path or drive name (see Figure 6.5). You can use other class methods for getting the directory path (GetPathName) or file extension (GetFileExt).

Figure 6.5. Displaying the selected filename.

NOTE

You can display a dialog box to users in two modes: modal and modeless. A modal dialog halts all other user interaction while it's displayed. Users can't do anything else in the application until the dialog is closed. A good example of a modal dialog is a message box where users can't continue working with the application until they click a button in the message box.

A modeless dialog can be open while users do something else in the application; it doesn't prevent users from performing other tasks while the dialog is visible. Good examples of modeless dialogs are the Find and Find and Replace dialogs in Microsoft Word. You can leave these dialogs open onscreen while you are still editing the document that you are searching.

MFC Note: The CFileDialog Class

The CFileDialog class encapsulates the functionality of the Open and Save File dialogs built into the Windows operating system. These enable you to provide users of your application with the same dialogs for finding and specifying files used in most other Windows applications. Table 6.7 lists the primary functions that you'll use with the CFileDialog class.

Table 6.7 Primary CFileDialog Member Functions

Function

Description

GetPathName

Returns the full path of the specified file

GetFileName

Returns the specified filename

GetFileExt

Returns the extension of the specified file

GetFileTitle

Returns the name of the file without the extension (for instance, if you selected the file "MyFile.txt", this function would return "MyFile")


NOTE

All methods listed in Table 6.7 shouldn't be called until after the DoModal method is called and returned with the IDOK return value. This same rule applies to all methods listed on the other common dialogs in the next few tables, unless otherwise specified.

MFC Note: The CFontDialog Class

The CFontDialog class encapsulates the standard font selection dialog built into Windows. This class enables you to provide your application users with a standard font selection dialog that they will be familiar with through use in other Windows applications. Table 6.8 lists the primary member methods for the CFontDialog class.

Table 6.8 Primary CFontDialog Member Functions

Function

Description

GetFaceName

Returns the name of the selected font.

GetStyleName

Returns the style of the selected font (a font style may have multiple fonts available).

GetSize

Returns the size specified for the selected font.

GetColor

Returns the color specified for the selected font.

GetWeight

Returns the weight specified for the selected font.

IsStrikeOut

Returns a Boolean value specifying whether the selected font was specified with the Strike Out attribute selected.

IsUnderline

Returns a Boolean value specifying whether the selected font was specified with the Underline attribute selected.

IsBold

Returns a Boolean value specifying whether the selected font was specified with the Bold attribute selected.

IsItalic

Returns a Boolean value specifying whether the selected font was specified with the Italic attribute selected.


MFC Note: The CColorDialog Class

The CColorDialog class encapsulates the standard color-picker dialog used in many Windows applications. This dialog is used to get the RGB value for the specified color, which can then be passed into any GDI method that requires a color value (you'll learn more about this in a couple of days). Table 6.9 lists the common methods used with the CColorDialog class.

Table 6.9 Primary CColorDialog Member Functions

Function

Description

GetColor

Returns the selected color.

GetSavedCustomColors

Returns an array of colors that users created.

SetCurrentColor

Specifies the current color selection. Call this method before calling the DoModal method.


MFC Note: The CPageSetupDialog Class

The CPageSetupDialog class encapsulates the Page Setup dialog that's often used with printing functionality. It can be called to allow users to specify the printer to be used, page size, and margins of the printed output. Table 6.10 lists the common methods used with the CPageSetupDialog class.

Table 6.10 Primary CPageSetupDialog Member Functions

Function

Description

CreatePrinterDC

Returns a device context that can be used for printing.

GetDeviceName

Returns the name of the selected printer.

GetDevMode

Returns a structure containing information about the selected printer and its capabilities (i.e. color or black and white).

GetMargins

You pass this method two pointers to either a CRect class or a RECT structure, and it populates the class or structures with the dimensions of the margins and print area.

GetPaperSize

This method returns a CSize class, which specifies the current paper size.

GetDriverName

Returns the name of the selected printer driver.

GetPortName

Returns the name of the selected output port.


MFC Note: The CPrintDialog Class

The CPrintDialog class encapsulates the standard Print dialog used in most Windows applications. This class contains most of the methods in the CPageSetupDialog, except for GetPaperSize and GetMargin. All the rest of the functions in Table 6.10 are available in the CPrintDialog class. Table 6.11 lists the other primary functions in this class.

Table 6.11 Primary CPrintDialog Member Functions

Function

Description

GetCopies

Returns the number of copies specified to be printed.

GetFromPage

Returns the starting page number when a range of pages have been specified to be printed.

GetToPage

Returns the ending page number when a range of pages have been specified to be printed.

GetPrinterDC

Returns a handle to the device context for the printer specified.

PrintAll

Returns a Boolean value specifying whether to print all pages of the current document.

PrintCollate

Returns a Boolean value specifying whether users requested that the printed output be collated.

PrintRange

Returns a Boolean value specifying whether users specified a range of pages to be printed.

PrintSelection

Returns a Boolean value specifying whether to print only the selected items or pages.


NOTE

Unlike with the CPageSetupDialog, you can call the CreatePrinterDC method without having called the DoModal method. In fact, you don't have to show the dialog at all, but you can use the class just to get the printer information and device context, so you can print to the current printer without displaying a dialog.

MFC Note: The CFindReplaceDialog Class

The CFindReplaceDialog class encapsulates the standard find/replace dialog used in many Windows applications. Unlike the other common dialogs, this dialog isn't modal, but instead enables users to interact with the parent window the entire time it's visible. Because of this difference, you don't call the DoModal method to display this dialog, but instead call the Create method.

The Create method requires two parameters but can take up to five parameters:

  • The first parameter, a Boolean value, specifies whether the dialog is a find-only dialog or a find-and-replace dialog. If TRUE is passed as the first parameter, a find-only dialog is displayed. If FALSE is passed in this parameter, a find-and-replace dialog is displayed.

  • The second parameter is the string to be searched for.

  • The third parameter (which is optional) is the replacement string.

  • The fourth parameter specifies which direction to search. The default direction is down, which is specified with the FR_DOWN constant. The up direction is specified by passing 0 in the fourth parameter.

  • The final parameter is a pointer to the parent window.

Because CFindReplaceDialog is a non-modal dialog, it requires a different usage in your application. First, don't declare a CFindReplaceDialog variable, but instead declare a pointer to a CFindReplaceDialog instance, and then use the new keyword to create the instance of the dialog:

// In the class header declaration (a class-level variable, 
// declared in the header file)
CFindReplaceDialog *m_pFRDlg;
...
// In the class source code (prior to first use, somewhere in
// the source code file)
m_pFRDlg = new CFindReplaceDialog;

Second, you need to register parent window to receive the messages from the CFindReplaceDialog. Near the top of the source code file for the class that will be receiving the messages, you need to declare a message ID variable:

static UINT WM_FINDREPLACE = ::RegisterWindowMessage(FINDMSGSTRING);

After you register the message from the CFindReplaceDialog, add the function to receive and handle those messages. First, you need to add the function to your class that will be receiving the messages. The function should be defined as returning a long data type, have protected access, and take two parameters: WPARAM for the data type and the LPARAM data type. After you add the function to your class, open the class definition (in the header file) and add the afx_msg keyword in front of the function definition. The class header definition for this function should look something like the following:

class CMyClass : public CWnd
{
...
protected:
[ic:Input]afx_msg long OnFindReplace(WPARAM wParam, LPARAM lParam);
  // Some other afx_msg functions here that the MFC Wizards added
  DECLARE_MESSAGE_MAP()
...
};

Finally, to set up your class for receiving message from the CFindReplaceDialog class, add an entry in the message map near the top of your source code file. When you look at the message map, you'll find many entries that have been already added by the MFC Wizards. You'll add a new entry using the ON_REGISTERED_MESSAGE macro, as follows:

BEGIN_MESSAGE_MAP(CMyClass, CWnd)
  ...
[ic:Input]ON_REGISTERED_MESSAGE(WM_FINDREPLACE, OnFindReplace)
END_MESSAGE_MAP()

Now your class is ready to receive and process event messages from the CFindReplaceDialog class. The way this works is that event messages are sent out from the Find/Replace dialog whenever users perform an action such as clicking the Find Next or Replace buttons. These messages are routed to the message map, through the ON_REGISTERED_MESSAGE macro, to the function you defined to handle these messages (see Figure 6.6).

Figure 6.6. Find/Replace message routing.

In your message handling function, the primary member functions of the CFindReplaceDialog class that you'll be calling to determine what action users are taking are found in Table 6.12.

Table 6.12 Primary CFindReplaceDialog Member Functions

Function

Description

FindNext

Returns a Boolean value indicating whether users want to find the next occurrence of the specified string.

GetFindString

Returns the string entered by users to be found.

GetReplaceString

Returns the string users entered to replace the find string.

IsTerminating

Returns a Boolean value specifying whether users have chosen to close the Find/Replace dialog.

MatchCase

Returns a Boolean value specifying whether users want to match the case of the find string.

MatchWholeWord

Returns a Boolean value indicating whether users want to find whole-word matches of the find string.

ReplaceAll

Returns a Boolean value indicating whether users want to replace all occurrences of the find string.

ReplaceCurrent

Returns a Boolean value indicating whether users want to replace the current occurrence of the find string.

SearchDown

Returns a Boolean value indicating whether users want to search down from the current position in the data.


InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020