"Windows Programming" series Eighth: Common dialog box

Source: Internet
Author: User
Tags textout

In the previous article we learned the Basic programming of the menu, this article to understand the use of common dialog box. Windows systems are currently the most popular desktop system, and because Windows has a standardized, unified and user-friendly interface, such as menus, toolbars, status bars, and individual controls. Of course, in addition to these individual controls, for Windows itself, such as file Open, Save dialog box, Font dialog, Color dialog box, and so on, will be used in many third-party applications. So Microsoft has long known that this reality will exist, so Windows makes this common public conversation a unified interface function for use by Windows itself and third-party developers.

The common dialog boxes provided by Windows differ in different versions, but common dialog boxes are: Color selection dialog, open File Dialog, save file Dialog, font selection dialog, Find dialog box, Replace dialog box, Print dialog box, Print Setup dialog, and so on.

This article takes the most common file Open/Save dialog boxes, font dialogs, color dialogs as examples to learn how to create these dialog boxes, other dialogs are similar in use, and there are basic usages on MSDN.

To use a common dialog box function, you need to include the Commdlg.h header file, and the related data structure and function definitions are defined in the header file.

    • File Open dialog box

File Open dialog box is mainly used to select the required files, the selected file full path name to the user, as to the full path of the file after the operation is entirely the developer's own decision. This means that it provides a common operating interface for selecting any file in the computer. The API functions are defined as follows:

BOOL GetOpenFileName (Lpopenfilename lpofn);

The parameter lpofn is defined as follows:

typedef struct tagofn {   dword          lStructSize;   HWND          hwndOwner;    HINSTANCE     hInstance;   LPCTSTR        lpstrFilter;   LPTSTR         lpstrcustomfilter;   dword         nmaxcustfilter;    DWORD         nFilterIndex;    lptstr        lpstrfile;   dword          nMaxFile;   LPTSTR         lpstrFileTitle;   DWORD          nmaxfiletitle;    lpctstr       lpstrinitialdir;   lpctstr        lpstrTitle;   DWORD          Flags;   WORD          nFileOffset;    WORD          nFileExtension;    LPCTSTR       lpstrDefExt;   LPARAM         lCustData;   LPOFNHOOKPROC lpfnHook;    lpctstr       lptemplatename;  #if   (_win32_winnt >=  0x0500)   void *        pvreserved;  dword          dwReserved;  DWORD          flagsex; #endif  //  (_win32_winnt >= 0x0500)} openfilename, *lpopenfilename; 


For each parameter member defined by this interface, please refer to MSDN's detailed explanations, here are some of the most commonly used:

Lpstrfilter: This parameter is used to set file format filtering for opening or saving conversations, such as file filtering scenarios in, I believe all of the reader friends have seen:

Lpstrfile: This parameter is used to save the selection file after the selection is finished.

nMaxFile: This parameter indicates the buffer character length above used to hold the result file.

Flags: This parameter is most commonly used to set whether multiple selections are available, others see MSDN.

    • File Save dialog box

The File Save dialog box is almost identical to the file Open dialog, with the same parameters. The function is also a common operating interface for selecting or creating a new file name and saving the path for the user to save the file. The API functions are defined as follows:

BOOL getsavefilename (Lpopenfilename lpofn);

The parameters of this function are exactly the same as above, except that some cannot be used in the File Save dialog function, and the file cannot be selected with multiple names.

    • Color selection dialog box

The dialog function provides a uniform interface for selecting colors, and the API functions are defined as follows:

BOOL Choosecolor (Lpchoosecolor LPCC);

Parameters LPCC The most important parameters:

Lpcustcolors, which points to an array of 16 values that contains the red, green, and Blue (RGB) values of the custom colors in the dialog box. If the user modifies these colors, the system updates the array with the new color values. If you want to save this new array in multiple Choosecolor functions, we should allocate a static memory space for the array.

Rgbresult: This parameter holds the selected color value.

    • Font selection dialog box:

This dialog function is used to browse and select fonts, including colors. The API functions are defined as follows:

BOOL Choosefont (Lpchoosefont lpcf);

dialog function after the end of the font in the rgbcolors parameter, we can use it to create the selected font.

Please refer to MSDN for additional members of each of these structures.

Below we demonstrate the basic usage of the above public dialog boxes with a demo program.

#include  <windows.h> #include  <tchar.h> #pragma  comment (linker, "\"/manifestdependency : Type= ' Win32 '   ' "name= ' microsoft.windows.common-controls '  " "version= ' 6.0.0.0 '   Processorarchitecture= ' * '   ' publickeytoken= ' 6595b64144ccf1df '  language= ' * ' \ ' ") #define  idc_file_ dialog  1001#define idc_color_dialog 1002#define idc_font_dialog   1003static tchar szappname[] = text ("CommonDialog"); static lresult callback  WndProc  (Hwnd, uint, wparam, lparam); Int winapi winmain (hinstance  Hinstance, hinstance hprevinstance, pstr szcmdline, int icmdshow) {      HWND     hWnd;     MSG       msg;     WNDCLASS wndclass;      Wndclass.style      &nbsP;  = cs_hredraw | cs_vredraw;     wndclass.lpfnwndproc    = wndproc;     wndclass.cbclsextra    =  0;     wndclass.cbWndExtra    = 0;      wndclass.hInstance     = hInstance;      Wndclass.hicon         = loadicon (NULL, IDI_APPLICATION );      wndclass.hcursor       = loadcursor ( Null, idc_arrow);     wndclass.hbrbackground =  (HBRUSH)   Getstockobject (White_brush);     wndclass.lpszmenuname  = null;      wndclass.lpszClassName = szAppName;     if  (! RegisterClass (&wndclass))      {          messagebox  (NULL,  text ("this program requires windows nt!"),  szappname, mb_iconerror);           return 0;     }           hwnd = createwindow (szAppName,              // window class name                            szAppName,             // window caption                           ws_ overlappedwindow,  // window style                           CW_USEDEFAULT,         // initial x position                           CW_USEDEFAULT,         // initial y position                            400,              //  initial x size                           300,               // initial y size                            NULL,             // parent  window handle                           NULL,              // window menu handle                            hinstance,        // program instance  handle                      &Nbsp;    null);             //  creation parameters          showwindow (HWnd,  icmdshow);      updatewindow (hWnd);           while  (GetMessage (&msg, null, 0, 0))      {           translatemessage (&msg);           dispatchmessage (&msg);     }      return msg.wparam;} Static lresult callback wndproc (Hwnd hwnd, uint message, wparam wparam ,  lparam lparam) {hdc hdc;switch  (message) {Case wm_create:createwindow (TEXT ("button"),  text ("File dialog"),  ws_child| ws_visible, 20, 40, 160, 40, hwnd,  (HMENU) idc_file_dialog, null, null); CreateWindow (TEXT ("button"),  text ("Color dialog"), ws_child| ws_visible, 20, 100, 160, 40, hwnd,  (HMENU) idc_color_dialog, null,  NULL); CreateWindow (TEXT ("button"),  text ("Font dialog"),  ws_child| ws_visible, 20, 160, 160, 40, hwnd,  (HMENU) idc_font_dialog, null, null ); Return 0;case wm_command:{int wmid = loword (WParam);switch  (wmId) {case  idc_file_dialog:{openfilename ofn; Tchar ext[] = text (". Dat"); Tchar szfile[max_path] = text ("Default"); Tchar szfilter[] = text ("Text file   (*.txt) \0*.txt\0")             text ("Data file   (*.dat) \0*.dat\0")    text ("all files  (*. *) \0* . *\0\0 "); ZeroMemory (&ofn, sizeof (ofn)); ofn.lstructsize  = sizeof (ofn); Ofn.hwndowner = hwnd;ofn.lpstrfilter  = szfilter;ofn.nfilterindex = 1;  //  1 to default show *.txt type file; 2 to default show  *.dat type file.ofn.lpstrfile = szfile;ofn.nmaxfile = max_path;o Fn.lpstrdefext  = ext;ofn. Flags = ofn_pathmustexist| ofn_overwriteprompt;if  (GetOpenFileName (&ofn))//getopenfilename, getsavefilename{                                                   //output the selected file to the window lptstr file =  Ofn.lpstrfile; //file is the file name Hdc = getdc (hWnd) that is saved or opened; TextOut (Hdc, 200, 50, ofn.lpstrfile, _tcslen (ofn.lpstrfile)); ReleaseDC (HWND,&NBSP;HDC);}} Break;case idc_color_dialog:{choosecolor cc;static colorref acrcustclr[16]; ZeroMemory (&cc, sizeof (cc)); cc.lstructsize  = sizeof (cc);cc.hwndowner= hwnd; cc.lpcustcolors =  (Lpdword) acrcustclr;if  (Choosecolor (&AMP;CC)) {                                                   //draw a solid rectangle rect rect = {240, 100, 340 with the selected color, &NBSP;140};HDC&NBSP;=&NBSP;GETDC (HWND); Hbrush hbrush = createsolidbrush (Cc.rgbresult); SelectObject (Hdc, hbrush); FillRect (Hdc, &rect, hbrush);D eleteobject (Hbrush); ReleaseDC (HWND,&NBSP;HDC);}} break;case idc_font_dialog:{choosefont cf; logfont lf; ZeroMemory (&cf, sizeof (CF)); cf.lstructsize = sizeof (cf); cf.hWNDOWNER&NBSP;&NBSP;&NBSP;=&NBSP;HWND;CF.LPLOGFONT&NBSP;&NBSP;&NBSP;=&NBSP;&AMP;LF;CF. flags       = cf_screenfonts | cf_effects;if  ( Choosefont (&AMP;CF)) {                                                  // Output a line of test text with the selected font tchar str[] = text ("font  test! "); Hfont hfont = createfontindirect (cf.lplogfont);D word rgbcurrent = cf.rgbcolors; HDC&NBSP;=&NBSP;GETDC (HWND); SelectObject (Hdc, hfont); SetTextColor (hdc, cf.rgbcolors); TextOut (Hdc, 200, 170, str, _tcslen (str));D eleteobject (Hfont); ReleaseDC (HWND,&NBSP;HDC);}} Break;default:break;}} Return 0;case wm_destroy:postquitmessage (0); return 0 ;} return defwindowproc  (hwnd, message, wparam, lparam);} 

The following demo run File selection dialog box is as follows:

The Select Color dialog box is as follows:

The Select Font dialog box is as follows:

After selecting three dialog boxes in the demo, the selected files, colors, and fonts are all drawn on the window:

The above just demonstrates the file open/save, color selection and Font selection dialog box, although only demonstrated the simplest features, but also the most basic, most commonly used features, can meet many application needs, more functions and usage please refer to MSDN, learn to check MSDN is a prerequisite for development on the Windows platform.


focus on the public platform: the Programmer Interaction Alliance (coder_online), you can get the first original technical articles, and (Java/c/c++/android/windows/linux) technology Daniel Friends, online communication programming experience, get programming basics, Solve programming problems. Programmer Interactive Alliance , Developer's own home.

Reprint Please specify the source http://www.coderonline.net/ , thank you for your cooperation!

"Windows Programming" series Eighth: Common dialog box

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.