Using Common Dialogs in C++.NET
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:
Declare a variable of the class type.
Set any properties that need to be configured before displaying the dialog to users.
Call the DoModal method of the class to display the dialog to users.
Capture the return value of the DoModal method to determine whether the users clicked OK or Cancel.
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. |