home *** CD-ROM | disk | FTP | other *** search
/ Liren Large Software Subsidy 7 / 07.iso / c / c082_122 / 1.ddi / CMDLG31.ZIP / CMDLG.C next >
Encoding:
C/C++ Source or Header  |  1992-06-10  |  12.2 KB  |  359 lines

  1. // (C) Copyright 1992 by Borland International
  2. //
  3. // Cmdlg.c - Common Dialogs example in C
  4.  
  5. /*********************************************************************
  6. This program has example code that makes use of the Common Dialogs
  7. available in Windows 3.1.  It is meant to be a simple example using the
  8. C programming language.
  9.  
  10. The main window will have menu selections for opening a file, changing the
  11. font and changing the color used for the selected font.  When a file is
  12. selected the name will be displayed on the client area of the window.
  13.  
  14. The files needed to build this program are . . .
  15.  
  16. cmdlg.h                    Header file for application
  17. cmdlgr.h                   Header file for application and resources
  18. cmdlg.c                    Source file for application
  19. cmdlg.rc                   Resource file for application
  20. ***********************************************************************/
  21.  
  22. // Contains the necessary headers and definitions for this program
  23. #include "cmdlg.h"
  24.  
  25. /***  Global Variables  ***/
  26. char szName[256];
  27. COLORREF crColor;
  28. HFONT hfFont;
  29. BOOL tfFontLoaded;
  30. HINSTANCE hInst;    // current instance
  31.  
  32.  
  33. /*********************************************************************
  34. Using the OPENFILENAME structure and the Windows 3.1 API call
  35. GetOpenFileName() eases the selection of files for the programmer and for
  36. the user.  The WINHELP.EXE help file WIN31WH.HLP (found in the BORLANDC\BIN
  37. directory) contains a detailed description of the function call and its
  38. associated structure.  The Flags field of the structure is particularly
  39. useful when custimization is required.
  40. **********************************************************************/
  41. void CMUFileOpen( HWND hWnd )
  42. {
  43.     OPENFILENAME ofnTemp;
  44.     DWORD Errval;    // Error value
  45.     char buf[5];    // Error buffer
  46.     char Errstr[50]="GetOpenFileName returned Error #";
  47.     char szTemp[] = "All Files (*.*)\0*.*\0Text Files (*.txt)\0*.txt\0";
  48. /*
  49. Note the initialization method of the above string.  The GetOpenFileName()
  50. function expects to find a string in the OPENFILENAME structure that has
  51. a '\0' terminator between strings and an extra '\0' that terminates the
  52. entire filter data set.  Using the technique shown below will fail because
  53. "X" is really 'X' '\0' '\0' '\0' in memory.  When the GetOpenFileName()
  54. function scans szTemp it will stop after finding the extra trailing '\0'
  55. characters.
  56.  
  57.     char szTemp[][4] = { "X", "*.*", "ABC", "*.*", "" };
  58.  
  59. The string should be "X\0*.*\0ABC\0*.*\0".
  60.  
  61. Remember that in C or C++ a quoted string is automatically terminated with
  62. a '\0' character so   char "X\0";   would result in 'X' '\0' '\0' which
  63. provides the extra '\0' that GetOpenFileName() needs to see in order to
  64. terminate the scan of the string.  Just 'char ch "X";' would result in 'X'
  65. '\0' and GetOpenFileName() would wander off in memory until it lucked into
  66. a '\0' '\0' character sequence.
  67. */
  68.  
  69. /*
  70. Some Windows structures require the size of themselves in an effort to
  71. provide backward compatibility with future versions of Windows.  If the
  72. lStructSize member is not set the call to GetOpenFileName() will fail.
  73. */
  74.     ofnTemp.lStructSize = sizeof( OPENFILENAME );
  75.     ofnTemp.hwndOwner = hWnd;    // An invalid hWnd causes non-modality
  76.     ofnTemp.hInstance = 0;
  77.     ofnTemp.lpstrFilter = (LPSTR)szTemp;    // See previous note concerning string
  78.     ofnTemp.lpstrCustomFilter = NULL;
  79.     ofnTemp.nMaxCustFilter = 0;
  80.     ofnTemp.nFilterIndex = 1;
  81.     ofnTemp.lpstrFile = (LPSTR)szName;    // Stores the result in this variable
  82.     ofnTemp.nMaxFile = sizeof( szName );
  83.     ofnTemp.lpstrFileTitle = NULL;
  84.     ofnTemp.nMaxFileTitle = 0;
  85.     ofnTemp.lpstrInitialDir = NULL;
  86.     ofnTemp.lpstrTitle = "OPENFILENAME";    // Title for dialog
  87.     ofnTemp.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST;
  88.     ofnTemp.nFileOffset = 0;
  89.     ofnTemp.nFileExtension = 0;
  90.     ofnTemp.lpstrDefExt = "*";
  91.     ofnTemp.lCustData = NULL;
  92.     ofnTemp.lpfnHook = NULL;
  93.     ofnTemp.lpTemplateName = NULL;
  94. /*
  95. If the call to GetOpenFileName() fails you can call CommDlgExtendedError()
  96. to retrieve the type of error that occured.
  97. */
  98.     if(GetOpenFileName( &ofnTemp ) != TRUE)
  99.     {
  100.         Errval=CommDlgExtendedError();
  101.         if(Errval!=0)    // 0 value means user selected Cancel
  102.         {
  103.             sprintf(buf,"%ld",Errval);
  104.             strcat(Errstr,buf);
  105.             MessageBox(hWnd,Errstr,"WARNING",MB_OK|MB_ICONSTOP);
  106.         }
  107.  
  108.     }
  109.     InvalidateRect( hWnd, NULL, TRUE );    // Repaint to display the new name
  110. }
  111.  
  112. /*************************************************************************
  113. Using the CHOOSECOLOR structure and the Windows 3.1 API call ChooseColor(),
  114. eases the selection of colors for the programmer and for the user.  The
  115. comments for the File Open dialog regarding the help file and the structure
  116. size also apply to the color dialog.
  117. **************************************************************************/
  118. void CMUColor( HWND hWnd )
  119. {
  120.     CHOOSECOLOR ccTemp;
  121.     COLORREF crTemp[16];    // Important, sometimes unused, array
  122.  
  123.     ccTemp.lStructSize = sizeof( CHOOSECOLOR );
  124.     ccTemp.hwndOwner = hWnd;
  125.     ccTemp.hInstance = 0;
  126.     ccTemp.rgbResult = crColor;    // CC_RGBINIT flag makes this the default color
  127. /*
  128. lpCustColors must be set to a valid array of 16 COLORREF's, even if it
  129. is not used.  If it isn't you will probably fail with a GP fault in
  130. COMMDLG.DLL.
  131. */
  132.     ccTemp.lpCustColors = crTemp;
  133.     ccTemp.Flags = CC_PREVENTFULLOPEN | CC_RGBINIT;
  134.     ccTemp.lCustData = 0L;
  135.     ccTemp.lpfnHook = NULL;
  136.     ccTemp.lpTemplateName = NULL;
  137.     if( ChooseColor( &ccTemp ) == TRUE ) crColor = ccTemp.rgbResult;
  138.     InvalidateRect( hWnd, NULL, TRUE );
  139. }
  140.  
  141. /**************************************************************************
  142. Using the CHOOSEFONT structure and the Windows 3.1 API call ChooseFont()
  143. eases the selection of fonts for the programmer and for the user.  The
  144. comments for the File Open dialog regarding the help file and the structure
  145. size also apply to the font dialog.
  146. ***************************************************************************/
  147. void CMUFont( HWND hWnd )
  148. {
  149. /*
  150. The variables below are static so that multiple calls to the font dialog will
  151. retain previous user selections.
  152. */
  153.     static CHOOSEFONT cfTemp;
  154.     static LOGFONT lfTemp;
  155.  
  156.     if( tfFontLoaded == TRUE )    // cfTemp contains previous selections
  157.     {
  158.         cfTemp.Flags |= CF_INITTOLOGFONTSTRUCT;
  159.         cfTemp.rgbColors = crColor;
  160.     }
  161.     else
  162.     {
  163.         cfTemp.lStructSize = sizeof( CHOOSEFONT );
  164.         cfTemp.hwndOwner = hWnd;
  165.         cfTemp.hDC = 0;
  166.         cfTemp.lpLogFont = &lfTemp;    // Store the result here
  167.         cfTemp.Flags = CF_EFFECTS | CF_FORCEFONTEXIST | CF_SCREENFONTS;
  168.         cfTemp.rgbColors = crColor;    // Color and font dialogs use the same color
  169.         cfTemp.lCustData = 0L;
  170.         cfTemp.lpfnHook = NULL;
  171.         cfTemp.lpTemplateName = NULL;
  172.         cfTemp.hInstance = 0;
  173.         cfTemp.lpszStyle = NULL;
  174.         cfTemp.nFontType = SCREEN_FONTTYPE;
  175.         cfTemp.nSizeMin = 0;
  176.         cfTemp.nSizeMax = 0;
  177.     }
  178.     if( ChooseFont( &cfTemp ) == TRUE )
  179.     {
  180.         if( tfFontLoaded == TRUE )
  181.             DeleteObject( hfFont );
  182.         crColor = cfTemp.rgbColors;
  183.         hfFont = CreateFontIndirect( &lfTemp );
  184.         tfFontLoaded = TRUE;
  185.     }
  186.     InvalidateRect( hWnd, NULL, TRUE );
  187. }
  188.  
  189. /**********************************************************************/
  190. BOOL InitApplication(HINSTANCE hInstance)
  191. {
  192.     WNDCLASS  wc;
  193.  
  194.     // Fill in window class structure with parameters that describe the
  195.     // main window.
  196.  
  197.     wc.style = CS_HREDRAW | CS_VREDRAW;    // Class style(s).
  198.     wc.lpfnWndProc = (long (FAR PASCAL*)())MainWndProc;    // Function to retrieve messages for
  199.                                                         // windows of this class.
  200.     wc.cbClsExtra = 0;    // No per-class extra data.
  201.     wc.cbWndExtra = 0;    // No per-window extra data.
  202.     wc.hInstance = hInstance;    // Application that owns the class.
  203.     wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  204.     wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  205.     wc.hbrBackground = GetStockObject(WHITE_BRUSH);
  206.     wc.lpszMenuName = "CMDLGAPMENU";    // Name of menu resource in .RC file.
  207.     wc.lpszClassName = "CMDLG";    // Name used in call to CreateWindow.
  208.  
  209.     /* Register the window class and return success/failure code. */
  210.  
  211.     return (RegisterClass(&wc));
  212.  
  213. }
  214.  
  215.  
  216. /************************************************************************/
  217. BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
  218. {
  219.     HWND    hWnd;    // Main window handle.
  220.  
  221.     /* Save the instance handle in static variable, which will be used in  */
  222.     /* many subsequence calls from this application to Windows.            */
  223.  
  224.     hInst = hInstance;
  225.  
  226.     /* Create a main window for this application instance.  */
  227.  
  228.     hWnd = CreateWindow(
  229.         "CMDLG",                    // See RegisterClass() call.
  230.         "Common Dialog Example",    // Text for window title bar.
  231.         WS_OVERLAPPEDWINDOW,          // Window style.
  232.         CW_USEDEFAULT,                // Default horizontal position.
  233.         CW_USEDEFAULT,                  // Default vertical position.
  234.         CW_USEDEFAULT,                  // Default width.
  235.         CW_USEDEFAULT,                // Default height.
  236.         NULL,                            // Overlapped windows have no parent.
  237.         NULL,                            // Use the window class menu.
  238.         hInstance,                    // This instance owns this window.
  239.         NULL                            // Pointer not needed.
  240.     );
  241.  
  242.     /* If window could not be created, return "failure" */
  243.  
  244.     if (!hWnd)
  245.         return (FALSE);
  246.  
  247.     /* Make the window visible; update its client area; and return "success" */
  248.  
  249.     ShowWindow(hWnd, nCmdShow);    // Show the window
  250.     UpdateWindow(hWnd);            // Sends WM_PAINT message
  251.     return (TRUE);                // Returns the value from PostQuitMessage
  252.  
  253. }
  254.  
  255.  
  256. /****************************************************************************
  257.     FUNCTION: MainWndProc(HWND, unsigned, WORD, LONG)
  258. ****************************************************************************/
  259. long FAR PASCAL _export MainWndProc(HWND hWnd, unsigned message,
  260.                                     WORD wParam, LONG lParam)
  261. {
  262.     HFONT fTemp;    // Placeholder for the original font
  263.     RECT rTemp;     // Client are needed by DrawText()
  264.     HDC hdc;        // HDC for Window
  265.     PAINTSTRUCT ps;    // Paint Struct for BeginPaint call
  266.  
  267.     switch (message) {
  268.     case WM_CREATE: // Initialize Global vars
  269.             strcpy( szName, "" );           // Empty the file name string
  270.             crColor = RGB( 0, 0, 0 );       // Use black as the default color
  271.             hfFont = 0;                     // Empty the handle to the font
  272.             tfFontLoaded = FALSE;           // Set the font selected flag to false
  273.         return NULL;
  274.  
  275.     case WM_PAINT:
  276.     // Display the file name using the selected font in the selected color.
  277.  
  278.             hdc=BeginPaint(hWnd,&ps);
  279.             SetTextColor( hdc, crColor );
  280.             if( tfFontLoaded == TRUE )
  281.                 fTemp = (HFONT)SelectObject( hdc, hfFont );
  282.             GetClientRect( hWnd, &rTemp );
  283.             DrawText( hdc, szName, strlen( szName ), &rTemp, DT_CENTER | DT_WORDBREAK );
  284.             if( tfFontLoaded == TRUE )
  285.                 SelectObject( hdc, fTemp );
  286.             EndPaint(hWnd,&ps);
  287.         break;
  288.  
  289.     case WM_COMMAND:    // message: command from application menu
  290.         switch(wParam)
  291.         {
  292.             case CM_EXIT:
  293.                     DestroyWindow(hWnd);
  294.                 break;
  295.  
  296.             case CM_U_FILEOPEN:
  297.                     CMUFileOpen(hWnd);
  298.                 break;
  299.  
  300.             case CM_U_COLOR:
  301.                     CMUColor(hWnd);
  302.                 break;
  303.  
  304.             case CM_U_FONT:
  305.                     CMUFont(hWnd);
  306.                 break;
  307.  
  308.             case CM_U_HELPABOUT:
  309.                     MessageBox(hWnd,szCMDLGAPAbout,"About CMDLG",MB_OK);
  310.                 break;
  311.  
  312.             default:
  313.                 break;
  314.         }
  315.         break;
  316.  
  317.     case WM_QUIT:
  318.     case WM_DESTROY:    // message: window being destroyed
  319.             if( hfFont != 0 )
  320.                 DeleteObject( hfFont );
  321.             PostQuitMessage(0);
  322.         break;
  323.  
  324.     default:            // Passes it on if unproccessed
  325.         return (DefWindowProc(hWnd, message, wParam, lParam));
  326.     }
  327.     return (NULL);
  328. }
  329.  
  330. #pragma argsused
  331. /**************************************************************/
  332. int PASCAL WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
  333.                    LPSTR lpCmdLine, int nCmdShow)
  334. {
  335.     MSG msg;            // message
  336.     if (!hPrevInstance)    // Other instances of app running?
  337.     if (!InitApplication(hInstance))    // Initialize shared things
  338.         return (FALSE);    // Exits if unable to initialize
  339.  
  340.     /* Perform initializations that apply to a specific instance */
  341.  
  342.     if (!InitInstance(hInstance, nCmdShow))
  343.         return (FALSE);
  344.  
  345.     /* Acquire and dispatch messages until a WM_QUIT message is received. */
  346.  
  347.     while (GetMessage(&msg,    // message structure
  348.         NULL,    // handle of window receiving the message
  349.         NULL,    // lowest message to examine
  350.         NULL))    // highest message to examine
  351.     {
  352.     TranslateMessage(&msg);    // Translates virtual key codes
  353.     DispatchMessage(&msg);    // Dispatches message to window
  354.     }
  355.     return (msg.wParam);    // Returns the value from PostQuitMessage
  356. }
  357.  
  358. // End of file cmdlg.c
  359.