MFC – CArray ”; Previous Next CArray is a collection that is best used for data that is to be accessed in a random or non sequential manner. CArray class supports arrays that are like C arrays, but can dynamically shrink and grow as necessary. Array indexes always start at position 0. You can decide whether to fix the upper bound or enable the array to expand when you add elements past the current bound. Memory is allocated contiguously to the upper bound, even if some elements are null. Here is a list of CArray class methods. Sr.No. Name & Description 1 Add Adds an element to the end of the array; grows the array if necessary. 2 Append Appends another array to the array; grows the array if necessary 3 Copy Copies another array to the array; grows the array if necessary. 4 ElementAt Returns a temporary reference to the element pointer within the array. 5 FreeExtra Frees all unused memory above the current upper bound. 6 GetAt Frees all unused memory above the current upper bound. 7 GetCount Gets the number of elements in this array. 8 GetData Allows access to elements in the array. Can be NULL. 9 GetSize Gets the number of elements in this array. 10 GetUpperBound Returns the largest valid index. 11 InsertAt Inserts an element (or all the elements in another array) at a specified index. 12 IsEmpty Determines whether the array is empty. 13 RemoveAll Removes all the elements from this array. 14 RemoveAt Removes an element at a specific index. 15 SetAt Sets the value for a given index; array not allowed to grow. 16 SetAtGrow Sets the value for a given index; grows the array if necessary. 17 SetSize Sets the number of elements to be contained in this array. Following are the different operations on CArray objects − Create CArray Object To create a collection of CArray values or objects, you must first decide the type of values of the collection. You can use one of the existing primitive data types such as int, CString, double etc. as shown below; CArray<CString, CString>strArray; Add items To add an item you can use CArray::Add() function. It adds an item at the end of the array. In the OnInitDialog(), CArray object is created and three names are added as shown in the following code. CArray<CString, CString>strArray; //Add names to CArray strArray.Add(L”Ali”); strArray.Add(L”Ahmed”); strArray.Add(L”Mark”); Retrieve Items To retrieve any item, you can use the CArray::GetAt() function. This function takes one integer parameter as an index of the array. Step 1 − Let us look at a simple example, which will retrieve all the names. //Retrive names from CArray for (int i = 0; i < strArray.GetSize(); i++) { m_strText.Append(strArray.GetAt(i) + L”n”); } Step 2 − Here is the complete implementation of CMFCCArrayDlg::OnInitDialog() BOOL CMFCCArrayDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application”s main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CArray<CString, CString>strArray; //Add names to CArray strArray.Add(L”Ali”); strArray.Add(L”Ahmed”); strArray.Add(L”Mark”); //Retrive names from CArray for (int i = 0; i < strArray.GetSize(); i++) { m_strText.Append(strArray.GetAt(i) + L”n”); } UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } Step 3 − When the above code is compiled and executed, you will see the following output. Add Items in the Middle To add item in the middle of array you can use the CArray::.InsertAt() function. It takes two paramerters — First, the index and Second, the value. Let us insert a new item at index 1 as shown in the following code. BOOL CMFCCArrayDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application”s main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CArray<CString, CString>strArray; //Add names to CArray strArray.Add(L”Ali”); strArray.Add(L”Ahmed”); strArray.Add(L”Mark”); strArray.InsertAt(1, L”Allan”); //Retrive names from CArray for (int i = 0; i < strArray.GetSize(); i++) { m_strText.Append(strArray.GetAt(i) + L”n”); } UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } When the above code is compiled and executed, you will see the following output. You can now see the name Allan dded as the second index. Update Item Value To update item in the middle of array you can use the CArray::.SetAt() function. It takes two paramerters — First, the index and Second, the value. Let us update the third element in the array as shown in the following code. BOOL CMFCCArrayDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application”s main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CArray<CString, CString>strArray; //Add names to CArray strArray.Add(L”Ali”); strArray.Add(L”Ahmed”); strArray.Add(L”Mark”); strArray.InsertAt(1, L”Allan”); strArray.SetAt(2, L”Salman”); //Retrive names from CArray for (int i = 0; i < strArray.GetSize(); i++) { m_strText.Append(strArray.GetAt(i) + L”n”); } UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } When the above code is compiled and executed, you will see the following output. You can now see that the value of third element is updated. Copy Array To copy the entire array into another CArray object, you can use CArray::Copy() function. Step1 − Let us create another array and copy all the elements from first array as shown in the following code. BOOL CMFCCArrayDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Add “About…” menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu→AppendMenu(MF_SEPARATOR); pSysMenu→AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically
Category: mfc
MFC – GDI
MFC – GDI ”; Previous Next Windows provides a variety of drawing tools to use in device contexts. It provides pens to draw lines, brushes to fill interiors, and fonts to draw text. MFC provides graphic-object classes equivalent to the drawing tools in Windows. Drawing A device context is a Windows data structure containing information about the drawing attributes of a device such as a display or a printer. All drawing calls are made through a device-context object, which encapsulates the Windows APIs for drawing lines, shapes, and text. Device contexts allow device-independent drawing in Windows. Device contexts can be used to draw to the screen, to the printer, or to a metafile. CDC is the most fundamental class to draw in MFC. The CDC object provides member functions to perform the basic drawing steps, as well as members for working with a display context associated with the client area of a window. Given below is the list of methods in CDC class. Sr. No. Name & Description 1 AbortDoc Terminates the current print job, erasing everything the application has written to the device since the last call of the StartDoc member function. 2 AbortPath Closes and discards any paths in the device context. 3 AddMetaFileComment Copies the comment from a buffer into a specified enhanced-format metafile. 4 AlphaBlend Displays bitmaps that have transparent or semitransparent pixels. 5 AngleArc Draws a line segment and an arc, and moves the current position to the ending point of the arc. 6 Arc Draws an elliptical arc. 7 ArcTo Draws an elliptical arc. This function is similar to Arc, except that the current position is updated. 8 Attach Attaches a Windows device context to this CDC object. 9 BeginPath Opens a path bracket in the device context. 10 BitBlt Copies a bitmap from a specified device context. 11 Chord Draws a chord (a closed figure bounded by the intersection of an ellipse and a line segment). 12 CloseFigure Closes an open figure in a path. 13 CreateCompatibleDC Creates a memory-device context that is compatible with another device context. You can use it to prepare images in memory. 14 CreateDC Creates a device context for a specific device. 15 CreateIC Creates an information context for a specific device. This provides a fast way to get information about the device without creating a device context. 16 DeleteDC Deletes the Windows device context associated with this CDC object. 17 DeleteTempMap Called by the CWinApp idle-time handler to delete any temporary CDC object created by FromHandle. Also detaches the device context. 18 Detach Detaches the Windows device context from this CDC object. 19 DPtoHIMETRIC Converts device units into HIMETRIC units. 20 DPtoLP Converts device units into logical units. 21 Draw3dRect Draws a three-dimensional rectangle. 22 DrawDragRect Erases and redraws a rectangle as it is dragged. 23 DrawEdge Draws the edges of a rectangle. 24 DrawEscape Accesses drawing capabilities of a video display that are not directly available through the graphics device interface (GDI). 25 DrawFocusRect Draws a rectangle in the style used to indicate focus. 26 DrawFrameControl Draw a frame control. 27 DrawIcon Draws an icon. 28 DrawState Displays an image and applies a visual effect to indicate a state. 29 DrawText Draws formatted text in the specified rectangle. 30 DrawTextEx Draws formatted text in the specified rectangle using additional formats. 31 Ellipse Draws an ellipse. 32 EndDoc Ends a print job started by the StartDoc member function. 33 EndPage Informs the device driver that a page is ending. 34 EndPath Closes a path bracket and selects the path defined by the bracket into the device context. 35 EnumObjects Enumerates the pens and brushes available in a device context. 36 Escape Allows applications to access facilities that are not directly available from a particular device through GDI. Also allows access to Windows escape functions. Escape calls made by an application are translated and sent to the device driver. 37 ExcludeClipRect Creates a new clipping region that consists of the existing clipping region minus the specified rectangle. 38 ExcludeUpdateRgn Prevents drawing within invalid areas of a window by excluding an updated region in the window from a clipping region. 39 ExtFloodFill Fills an area with the current brush. Provides more flexibility than the FloodFill member function. 40 ExtTextOut Writes a character string within a rectangular region using the currently selected font. 41 FillPath Closes any open figures in the current path and fills the path”s interior by using the current brush and polygonfilling mode. 42 FillRect Fills a given rectangle by using a specific brush. 43 FillRgn Fills a specific region with the specified brush. 44 FillSolidRect Fills a rectangle with a solid color. 45 FlattenPath Transforms any curves in the path selected into the current device context, and turns each curve into a sequence of lines. 46 FloodFill Fills an area with the current brush. 47 FrameRect Draws a border around a rectangle. 48 FrameRgn Draws a border around a specific region using a brush. 49 FromHandle Returns a pointer to a CDC object when given a handle to a device context. If a CDC object is not attached to the handle, a temporary CDC object is created and attached. 50 GetArcDirection Returns the current arc direction for the device context. 51 GetAspectRatioFilter Retrieves the setting for the current aspect-ratio filter. 52 GetBkColor Retrieves the current background color. 53 GetBkMode Retrieves the background mode. 54 GetBoundsRect Returns the current accumulated bounding rectangle for the specified device context. 55 GetBrushOrg Retrieves the origin of the current brush. 56 GetCharABCWidths Retrieves the widths, in logical units, of consecutive characters in a given range from the current font. 57 GetCharABCWidthsI Retrieves the widths, in logical units, of consecutive glyph indices in a specified range from the current TrueType font. 58 GetCharacterPlacement Retrieves various types of information on a character string. 59 GetCharWidth Retrieves the fractional widths of consecutive characters in a given range from the current font. 60 GetCharWidthI Retrieves the widths, in logical coordinates, of
MFC – Document View
MFC – Document View ”; Previous Next The Document/View architecture is the foundation used to create applications based on the Microsoft Foundation Classes library. It allows you to make distinct the different parts that compose a computer program including what the user sees as part of your application and the document a user would work on. This is done through a combination of separate classes that work as an ensemble. The parts that compose the Document/View architecture are a frame, one or more documents, and the view. Put together, these entities make up a usable application. View A view is the platform the user is working on to do his or her job. To let the user do anything on an application, you must provide a view, which is an object based on the CView class. You can either directly use one of the classes derivedfrom CView or you can derive your own custom class from CView or one of its child classes. Document A document is similar to a bucket. For a computer application, a document holds the user”s data. To create the document part of this architecture, you must derive an object from the CDocument class. Frame As the name suggests, a frame is a combination of the building blocks, the structure, and the borders of an item. A frame gives “physical” presence to a window. It also defines the location of an object with regards to the Windows desktop. Single Document Interface (SDI) The expression Single Document Interface or SDI refers to a document that can present only one view to the user. This means that the application cannot display more than one document at a time. If you want to view another type of document of the current application, you must create another instance of the application. Notepad and WordPad are examples of SDI applications. Let us look into a simple example of single document interface or SDI by creating a new MFC dialog based application. Step 1 − Let us create a new MFC Application MFCSDIDemo with below mentioned settings. Step 2 − Select Single document from the Application type and MFC standard from Project Style. Step 3 − Click Finish to Continue. Step 4 − Once the project is created, run the application and you will see the following output. Multiple Document Interface (MDI) An application is referred to as a Multiple Document Interface, or MDI, if the user can open more than one document in the application without closing it. To provide this functionality, the application provides a parent frame that acts as the main frame of the computer program. Inside this frame, the application allows creating views with individual frames, making each view distinct from the other. Let us look into a simple example of multiple document interface or MDI by creating a new MFC dialog based application. Step 1 − Let us create a new MFC Application MFCMDIDemo with below mentioned settings. Step 2 − Select Multiple document from the Application type and MFC standard from Project Style. Step 3 − Click Finish to Continue. Step 4 − Once the project is created, run the application and you will see the following output. Step 5 − When you click on File → New menu option, it will create another child window as shown in the following snapshot. Step 6 − In Multiple Document Interface (MDI) applications, there is one main frame per application. In this case, a CMDIFrameWnd, and one CMDIChildWnd derived child frame for each document. Print Page Previous Next Advertisements ”;
MFC – Property Sheets
MFC – Property Sheets ”; Previous Next A property sheet, also known as a tab dialog box, is a dialog box that contains property pages. Each property page is based on a dialog template resource and contains controls. It is enclosed on a page with a tab on top. The tab names the page and indicates its purpose. Users click a tab in the property sheet to select a set of controls. To create property pages, let us look into a simple example by creating a dialog based MFC project. Once the project is created, we need to add some property pages. Visual Studio makes it easy to create resources for property pages by displaying the Add Resource dialog box, expanding the Dialog node and selecting one of the IDD_PROPPAGE_X items. Step 1 − Right-click on your project in solution explorer and select Add → Resources. Step 2 − Select the IDD_PROPPAGE_LARGE and click NEW. Step 3 − Let us change ID and Caption of this property page to IDD_PROPPAGE_1 and Property Page 1 respectively as shown above. Step 4 − Right-click on the property page in designer window. Step 5 − Select the Add Class option. Step 6 − Enter the class name and select CPropertyPage from base class dropdown list. Step 7 − Click Finish to continue. Step 8 − Add one more property page with ID IDD_PROPPAGE_2 and Caption Property Page 2 by following the above mentioned steps. Step 9 − You can now see two property pages created. To implement its functionality, we need a property sheet. The Property Sheet groups the property pages together and keeps it as entity. To create a property sheet, follow the steps given below − Step 1 − Right-click on your project and select Add > Class menu options. Step 2 − Select Visual C++ → MFC from the left pane and MFC Class in the template pane and click Add. Step 3 − Enter the class name and select CPropertySheet from base class dropdown list. Step 4 − Click finish to continue. Step 5 − To launch this property sheet, we need the following changes in our main project class. Step 6 − Add the following references in CMFCPropSheetDemo.cpp file. #include “MySheet.h” #include “PropPage1.h” #include “PropPage2.h” Step 7 − Modify the CMFCPropSheetDemoApp::InitInstance() method as shown in the following code. CMySheet mySheet(L”Property Sheet Demo”); CPropPage1 page1; CPropPage2 page2; mySheet.AddPage(&page1); mySheet.AddPage(&page2); m_pMainWnd = &mySheet; INT_PTR nResponse = mySheet.DoModal(); Step 8 − Here is the complete implementation of CMFCPropSheetDemo.cpp file. // MFCPropSheetDemo.cpp : Defines the class behaviors for the application. // #include “stdafx.h” #include “MFCPropSheetDemo.h” #include “MFCPropSheetDemoDlg.h” #include “MySheet.h” #include “PropPage1.h” #include “PropPage2.h” #ifdef _DEBUG #define new DEBUG_NEW #endif // CMFCPropSheetDemoApp BEGIN_MESSAGE_MAP(CMFCPropSheetDemoApp, CWinApp) ON_COMMAND(ID_HELP, &CWinApp::OnHelp) END_MESSAGE_MAP() // CMFCPropSheetDemoApp construction CMFCPropSheetDemoApp::CMFCPropSheetDemoApp() { // support Restart Manager m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART; // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CMFCPropSheetDemoApp object CMFCPropSheetDemoApp theApp; // CMFCPropSheetDemoApp initialization BOOL CMFCPropSheetDemoApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); AfxEnableControlContainer(); // Create the shell manager, in case the dialog contains // any shell tree view or shell list view controls. CShellManager *pShellManager = new CShellManager; // Activate “Windows Native” visual manager for enabling themes in MFC controls CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows)); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T(“Local AppWizard-Generated Applications”)); CMySheet mySheet(L”Property Sheet Demo”); CPropPage1 page1; CPropPage2 page2; mySheet.AddPage(&page1); mySheet.AddPage(&page2); m_pMainWnd = &mySheet; INT_PTR nResponse = mySheet.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK }else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel }else if (nResponse == -1) { TRACE(traceAppMsg, 0, “Warning: dialog creation failed, so application is terminating unexpectedly.n”); TRACE(traceAppMsg, 0, “Warning: if you are using MFC controls on the dialog, you cannot #define _AFX_NO_MFC_CONTROLS_IN_DIALOGS.n”); } // Delete the shell manager created above. if (pShellManager != NULL) { delete pShellManager; } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application”s message pump. return FALSE; } Step 9 − When the above code is compiled and executed, you will see the following dialog box. This dialog box contains two property pages. Print Page Previous Next Advertisements ”;
MFC – Getting Started
MFC – Getting Started ”; Previous Next In this chapter, we will look at a working MFC example. To create an MFC application, you can use wizards to customize your projects. You can also create an application from scratch. Create Project Using Project Templates Following are the steps to create a project using project templates available in Visual Studio. Step 1 − Open the Visual studio and click on the File → New → Project menu option. Step 2 − You can now see that the New Project dialog box is open. Step 3 − From the left pane, select Templates → Visual C++ → MFC Step 4 − In the middle pane, select MFC Application. Step 5 − Enter the project name ‘MFCDemo’ in the Name field and click OK to continue. You will see the following dialog. Step 6 − Click Next. Step 7 − Select the options which are shown in the dialog box given above and click Next. Step 8 − Uncheck all options and click Finish button. You can now see that the MFC wizard creates this Dialog Box and the project files by default. Step 9 − Run this application, you will see the following output. Create Project from Scratch You can also create an MFC application from scratch. To create an MFC application, you need to follow the following Steps. Step 1 − Open the Visual studio and click on the File → New → Project menu option. Step 2 − You can now see the New Project dialog box. Step 3 − From the left pane, select Templates → Visual C++ → General. Step 4 − In the middle pane, select Empty Step 5 − Enter project name ‘MFCDemoFromScratch’ in the Name field and click OK to continue. You will see that an empty project is created. Step 6 − To make it an MFC project, right-click on the project and select Properties. Step 7 − In the left section, click Configuration Properties → General. Step 8 − Select the Use MFC in Shared DLL option in Project Defaults section and click OK. Step 9 − As it is an empty project now; we need to add a C++ file. So, right-click on the project and select Add → New Item… Step 10 − Select C++ File (.cpp) in the middle pane and enter file name in the Name field and click Add button. Step 11 − You can now see the main.cpp file added under the Source Files folder. Step 12 − Let us add the following code in this file. #include <iostream> using namespace std; void main() { cout << “***************************************n”; cout << “MFC Application Tutorial”; cout << “n***************************************”; getchar(); } Step 13 − When you run this application, you will see the following output on console. *************************************** MFC Application Tutorial *************************************** Print Page Previous Next Advertisements ”;
MFC – Dialog Boxes
MFC – Dialog Boxes ”; Previous Next In this chapter, we will be covering the Dialog boxes. Applications for Windows frequently communicate with the user through dialog boxes. CDialog class provides an interface for managing dialog boxes. The Visual C++ dialog editor makes it easy to design dialog boxes and create their dialog-template resources. Creating a dialog object is a two-phase operation − Construct the dialog object. Create the dialog window. Let us look into a simple example by creating a new Win32 project. Step 1 − Open the Visual studio and click on the File → New → Project menu option. Step 2 − You can now see the New Project dialog box. Step 3 − From the left pane, select Templates → Visual C++ → Win32. Step 4 − In the middle pane, select Win32 Project. Step 5 − Enter project name ‘MFCDialogDemo’ in the Name field and click OK to continue. You will see the following dialog. Step 6 − Click Next. Step 7 − Select the options shown in the dialog box given above and click Finish. Step 8 − An empty project is created. Step 9 − To make it a MFC project, right-click on the project and select Properties. Step 10 − In the left section, click Configuration Properties → General. Step 11 − Select the Use MFC in Shared DLL option in Project Defaults section and click OK. Step 12 − Add a new source file. Step 13 − Right-click on your Project and select Add → New Item. Step 14 − In the Templates section, click C++ File (.cpp) Step 15 − Set the Name as Example and click Add. Step 16 − To create an application, we need to add a class and derive it from the MFC”s CWinApp. #include <afxwin.h> class CExample : public CWinApp { public: BOOL InitInstance(); }; Dialog Box Creation Step 1 − To create a dialog box, right-click on the Resource Files folder in solution explorer and select Add → Resource. Step 2 − In the Add Resource dialog box, select Dialog and click New. Step 3 − A dialog box requires some preparation before actually programmatically creating it. Step 4 − A dialog box can first be manually created as a text file (in a resource file). Step 5 − You can now see the MFCDialogDemo.rc file created under Resource Files. Step 6 − The resource file is open in designer. The same can be opened as a text file. Rightclick on the resource file and select Open With. Step 7 − Select the Source Code (Text) editor and click Add button. Step 8 − Go back to the designer and right-click on the dialog and select Properties. Step 9 − You need to choose out of the many options. Step 10 − Like most other controls, a dialog box must be identified. The identifier (ID) of a dialog box usually starts with IDD_, Let us change the ID to IDD_EXAMPLE_DLG. Dialog Location A dialog box must be “physically” located on an application. Because a dialog box is usually created as a parent to other controls, its location depends on its relationship to its parent window or to the desktop. If you look and the Properties window, you see two fields, X Pos and Y Pos. X is the distance from the left border of the monitor to the left border of the dialog box. Y is the distance from the top border of the monitor to the top border of the dialog box. By default, these fields are set to zero. You can also change as shown above. If you specify these two dimensions as 0, the left and top borders of the dialog box would be set so the object appears in the center-middle of the screen. Dialog Box Dimensions The dimensions of a dialog box refer to its width and its height. You can resize the width and height with the help of mouse in designer window. You can see the changes in width and height on the Status Bar. Dialog Box Methods The base class used for displaying dialog boxes on the screen is CDialog class. To create a dialog box, we need to derive a class from CDialog. The CDialog class itself provides three constructors which are as follows − CDialog(); CDialog(UINT nIDTemplate, CWnd* pParentWnd = NULL); CDialog(LPCTSTR lpszTemplateName, CWnd* pParentWnd = NULL); Let us create another class CExampleDlg and derive it from CDialog. We will implement its default constructor destructor as shown in the following code. class CExampleDlg : public CDialog { public: enum { IDD = IDD_EXAMPLE_DLG }; CExampleDlg(); ~CExampleDlg(); }; CExampleDlg::CExampleDlg():CDialog(CExampleDlg::IDD) { } CExampleDlg::~CExampleDlg() { } We need to instantiate this dialog on CExample::InitInstance() method as shown in the following code. BOOL CExample::InitInstance() { CExampleDlg myDlg; m_pMainWnd = &myDlg; return TRUE; } Modal Dialog Boxes There are two types of dialog boxes − modeless and modal. Modal and modeless dialog boxes differ by the process used to create and display them. Modeless Dialog Box For a modeless dialog box, you must provide your own public constructor in your dialog class. To create a modeless dialog box, call your public constructor and then call the dialog object”s Create member function to load the dialog resource. You can call Create either during or after the constructor call. If the dialog resource has the property WS_VISIBLE, the dialog box appears immediately. If not, you must call its ShowWindow member function. Modal Dialog To create a modal dialog box, call either of the two public constructors declared in CDialog. Next, call the dialog object”s DoModal member function to display the dialog box and manage interaction with it until the user chooses OK or Cancel. This management by DoModal is what makes the dialog box modal. For modal dialog boxes, DoModal loads the dialog resource. Step 1 − To display the dialog box as modal, in the CExample::InitInstance() event call the DoModal() method using your dialog variable −
MFC – Windows Layout
MFC – Windows Layout ”; Previous Next Layout of controls is very important and critical for application usability. It is used to arrange a group of GUI elements in your application. There are certain important things to consider while selecting layout − Positions of the child elements. Sizes of the child elements. Adding controls Let us create new Dialog based MFC Project MFCLayoutDemo. Step 1 − Once the project is created, you will see the following screen. Step 2 − Delete the TODO from the dialog box. Step 3 − Drag some controls from the Toolbox which you can see on the left side. (We will drag one Static Text and one Edit Control as shown in the following snapshot). Step 4 − Change the Caption of the Static Text to Name. Control Grid Control grid is the guiding grid dots, which can help in positioning of the controls you are adding at the time of designing. To enable the control grid, you need to click the Toggle Grid button in the toolbar as shown in the following snapshot. Controls Resizing After you have added a control to a dialog box, it assumes either its default size or the size you drew it with. To help with the sizes of controls on the form or dialog box, Visual Studio provides a visual grid made of black points. To resize a control, that is, to give it a particular width or height, position the mouse on one of the handles and drag it in the desired direction. You can now resize the controls with the help of this dotted grid. Controls Positions The controls you position on a dialog box or a form assume their given place. Most of the time, these positions are not practical. You can move them around to any position of your choice. Let us add some more controls − Step 1 − To move a control, click and drag it in the desired direction until it reaches the intended position. Step 2 − To move a group of controls, first select them. Then drag the selection to the desired location. Let us select the Static Texts and Edit Controls. Step 3 − Move these selected controls to the left side. To help with positioning the controls, Visual Studio provides the Dialog toolbar with the following buttons. Step 1 − Let us align the Check box and Static Text controls to the left by selecting all these controls. Step 2 − Select the Format → Align → Lefts. Step 3 − You can now see all these controls are aligned to the left. Tab Ordering The controls you add to a form or a dialog box are positioned in a sequence that follows the order they were added. When you add control(s) regardless of the section or area you place the new control, it is sequentially positioned at the end of the existing controls. If you do not fix it, the user would have a hard time navigating the controls. The sequence of controls navigation is also known as the tab order. To change the tab, you can either use the Format → Tab Order menu option or you can also use the Ctrl + D shortcut. Let us press Ctrl + D. You can now see the order in which all these controls are added to this dialog box. To Change the order or sequence of controls, click on all the controls in sequence in which you want to navigate. In this example, we will first click on the checkbox followed by Name and Address Edit controls. Then click OK and Cancel as shown in the following snapshot. Let us run this application and you will see the following output. Print Page Previous Next Advertisements ”;
MFC – Windows Controls
MFC – Windows Control ”; Previous Next Windows controls are objects that users can interact with to enter or manipulate data. They commonly appear in dialog boxes or on toolbars. There are various types of controls − A text based control which is used to display text to the user or request text from the user. A list based control displays a list of items. A progress based control is used to show the progress of an action. A static control can be used to show colors, a picture or something that does not regularly fit in the above categories. Sr.No. Controls & Description 1 Static Control A static control is an object that displays information to the user without his or her direct intervention. It can be used to show colors, a geometric shape, or a picture such as an icon, a bitmap, or an animation. 2 Animation Control An animation control is a window that displays an Audio clip in AVI format. An AVI clip is a series of bitmap frames, like a movie. Animation controls can only play simple AVI clips, and they do not support sound. It is represented by the CAnimateCtrl class. 3 Button A button is an object that the user clicks to initiate an action. Button control is represented by CButton class. 4 Bitmap Button A bitmap button displays a picture or a picture and text on its face. This is usually intended to make the button a little explicit. A bitmap button is created using the CBitmapButton class, which is derived from CButton. 5 Command Button A command button is an enhanced version of the regular button. It displays a green arrow icon on the left, followed by a caption in regular size. Under the main caption, it can display another smaller caption that serves as a hint to provide more information. 6 Static Text A static control displays a text string, box, rectangle, icon, cursor, bitmap, or enhanced metafile. It is represented by CStatic class. It can be used to label, box, or separateother controls. A static control normally takes no input and provides no output. 7 List Box A list box displays a list of items, such as filenames, that the user can view and select. A List box is represented by CListBox class. In a single-selection list box, the user can select only one item. In a multiple-selection list box, a range of items can be selected. When the user selects an item, it is highlighted and the list box sends a notification message to the parent window. 8 Combo Boxes A combo box consists of a list box combined with either a static control or edit control. it is represented by CComboBox class. The list-box portion of the control may be displayed at all times or may only drop down when the user selects the drop-down arrow next to the control. 9 Radio Buttons A radio button is a control that appears as a dot surrounded by a round box. In reality, a radio button is accompanied by one or more other radio buttons that appear and behave as a group. 10 Checkboxes A checkbox is a Windows control that allows the user to set or change the value of an item as true or false. 11 Image Lists An Image List is a collection of same-sized images, each of which can be referred to by its zero-based index. Image lists are used to efficiently manage large sets of icons or bitmaps. Image lists are represented by CImageList class. 12 Edit Box An Edit Box is a rectangular child window in which the user can enter text. It is represented by CEdit class. 13 Rich Edit A Rich Edit Control is a window in which the user can enter and edit text. The text can be assigned character and paragraph formatting, and can include embedded OLE objects. It is represented by CRichEditCtrl class. 14 Group Box A group box is a static control used to set a visible or programmatic group of controls. The control is a rectangle that groups other controls together. 15 Spin Button A Spin Button Control (also known as an up-down control) is a pair of arrow buttons that the user can click to increment or decrement a value, such as a scroll position or a number displayed in a companion control. it is represented by CSpinButtonCtrl class. 16 Managing the Updown Control It manages the Updown Controls. 17 Progress Control A progress bar control is a window that an application can use to indicate the progress of a lengthy operation. It consists of a rectangle that is gradually filled, from left to right, with the system highlight color as an operation progresses. It is represented by CProgressCtrl class. 18 Progress Bars A progress bars is a window that an application can use to indicate the progress of a operation. 19 Timer A timer is a non-spatial object that uses recurring lapses of time from a computer or fromyour application. To work, every lapse of period, the control sends a message to the operating system. Unlike most other controls, the MFC timer has neither a button to represent it nor a class. To create a timer, you simply call the CWnd::SetTimer() method. This function call creates a timer for your application. Like the other controls, a timer uses an identifier. 20 Date & Time Picker The date and time picker control (CDateTimeCtrl) implements an intuitive and recognizable method of entering or selecting a specific date. The main interface of the control is similar in functionality to a combo box. However, if the user expands the control, a month calendar control appears (by default), allowing the user to specify a particular date. When a date is chosen, the month calendar control automatically disappears. 21 Picture If you need to display a picture for your application, Visual C++ provides a special control for that purpose. 22 Image Editor The Image editor has
MFC – VC++ Projects
MFC – VC++ Projects ”; Previous Next In this chapter, we will be covering the different types of VC++ projects. Visual Studio includes several kinds of Visual C++ project templates. These templates help to create the basic program structure, menus, toolbars, icons, references, and include statements that are appropriate for the kind of project you want to create. Following are some of the salient features of the templates. It provides wizards for many of these project templates and helps you customize your projects as you create them. Once the project is created, you can build and run the application. You don”t have to use a template to create a project, but in most cases it”s more efficient to use project templates. It”s easier to modify the provided project files and structure than it is to create them from scratch. In MFC, you can use the following project templates. Sr.No. Project Template & Description 1 MFC Application An MFC application is an executable application for Windows that is based on the Microsoft Foundation Class (MFC) Library. The easiest way to create an MFC application is to use the MFC Application Wizard. 2 MFC ActiveX Control ActiveX control programs are modular programs designed to give a specific type of functionality to a parent application. For example, you can create a control such as a button for use in a dialog, or toolbar or on a Web page. 3 MFC DLL An MFC DLL is a binary file that acts as a shared library of functions that can be used simultaneously by multiple applications. The easiest way to create an MFC DLL project is to use the MFC DLL Wizard. Following are some General templates which can also be used to create MFC application − Sr.No. Project Template & Description 1 Empty Project Projects are the logical containers for everything that”s needed to build your application. You can then add more new or existing projects to the solution if necessary. 2 Custom Wizard The Visual C++ Custom Wizard is the tool to use when you need to create a new custom wizard. The easiest way to create a custom wizard is to use the Custom Wizard. Print Page Previous Next Advertisements ”;
MFC – Home
MFC Tutorial PDF Version Quick Guide Resources Job Search Discussion The Microsoft Foundation Class (MFC) library provides a set of functions, constants, data types, and classes to simplify creating applications for the Microsoft Windows operating systems. In this tutorial, you will learn all about how to start and create Windows-based applications using MFC. Audience This tutorial is designed for all those developers who are keen on developing best-in-class applications using MFC. The tutorial provides a hands-on approach with step-by-step program examples, source codes, and illustrations that will assist the developers to learn and put the acquired knowledge into practice. Prerequisites To gain advantage of this tutorial you need to be familiar with programming for Windows. You also need to know the basics of programming in C++ and understand the fundamentals of object-oriented programming. Print Page Previous Next Advertisements ”;