MFC – Serialization ”; Previous Next Serialization is the process of writing or reading an object to or from a persistent storage medium such as a disk file. Serialization is ideal for situations where it is desired to maintain the state of structured data (such as C++ classes or structures) during or after the execution of a program. When performing file processing, the values are typically of primitive types (char, short, int, float, or double). In the same way, we can individually save many values, one at a time. This technique doesn”t include an object created from (as a variable of) a class. The MFC library has a high level of support for serialization. It starts with the CObject class that is the ancestor to most MFC classes, which is equipped with a Serialize() member function. Let us look into a simple example by creating a new MFC project. Step 1 − Remove the TODO line and design your dialog box as shown in the following snapshot. Step 2 − Add value variables for all the edit controls. For Emp ID and Age mentioned, the value type is an integer as shown in the following snapshot. Step 3 − Add the event handler for both the buttons. Step 4 − Let us now add a simple Employee class, which we need to serialize. Here is the declaration of Employee class in header file. class CEmployee : public CObject { public: int empID; CString empName; int age; CEmployee(void); ~CEmployee(void); private: public: void Serialize(CArchive& ar); DECLARE_SERIAL(CEmployee); }; Step 5 − Here is the definition of Employee class in source (*.cpp) file. IMPLEMENT_SERIAL(CEmployee, CObject, 0) CEmployee::CEmployee(void) { } CEmployee::~CEmployee(void) { } void CEmployee::Serialize(CArchive& ar) { CObject::Serialize(ar); if (ar.IsStoring()) ar << empID << empName << age; else ar >> empID >> empName >> age; } Step 6 − Here is the implementation of Save button event handler. void CMFCSerializationDlg::OnBnClickedButtonSave() { // TODO: Add your control notification handler code here UpdateData(TRUE); CEmployee employee; CFile file; file.Open(L”EmployeeInfo.hse”, CFile::modeCreate | CFile::modeWrite); CArchive ar(&file, CArchive::store); employee.empID = m_id; employee.empName = m_strName; employee.age = m_age; employee.Serialize(ar); ar.Close(); } Step 7 − Here is the implementation of Open button event handler. void CMFCSerializationDlg::OnBnClickedButtonOpen() { // TODO: Add your control notification handler code here UpdateData(TRUE); CFile file; file.Open(L”EmployeeInfo.hse”, CFile::modeRead); CArchive ar(&file, CArchive::load); CEmployee employee; employee.Serialize(ar); m_id = employee.empID; m_strName = employee.empName; m_age = employee.age; ar.Close(); file.Close(); UpdateData(FALSE); } Step 8 − When the above code is compiled and executed, you will see the following output. Step 9 − Enter the info in all the fields and click Save and close this program. Step 10 − It will save the data. Run the application again and click open. It will load the Employee information. Print Page Previous Next Advertisements ”;
Category: mfc
MFC – Strings
MFC – Strings ”; Previous Next Strings are objects that represent sequences of characters. The C-style character string originated within the C language and continues to be supported within C++. This string is actually a one-dimensional array of characters which is terminated by a null character ””. A null-terminated string contains the characters that comprise the string followed by a null. Here is the simple example of character array. char word[12] = { ”H”, ”e”, ”l”, ”l”, ”o”, ” ”, ”W”, ”o”, ”r”, ”l”, ”d”, ”” }; Following is another way to represent it. char word[] = “Hello, World”; Microsoft Foundation Class (MFC) library provides a class to manipulate string called CString. Following are some important features of CString. CString does not have a base class. A CString object consists of a variable-length sequence of characters. CString provides functions and operators using a syntax similar to that of Basic. Concatenation and comparison operators, together with simplified memory management, make CString objects easier to use than ordinary character arrays. Here is the constructor of CString. Sr.No. Method & Description 1 CString Constructs CString objects in various ways Here is a list of Array Methods − Sr.No. Method & Description 1 GetLength Returns the number of characters in a CString object. 2 IsEmpty Tests whether a CString object contains no characters. 3 Empty Forces a string to have 0 length. 4 GetAt Returns the character at a specified position. 5 SetAt Sets a character at a specified position. Here is a list of Comparison Methods − Sr.No. Method & Description 1 Compare Compares two strings (case sensitive). 2 CompareNoCase Compares two strings (case insensitive). Here is a list of Extraction Methods − Sr.No. Method & Description 1 Mid Extracts the middle part of a string (like the Basic MID$ function). 2 Left Extracts the left part of a string (like the Basic LEFT$ function). 3 Right Extracts the right part of a string (like the Basic RIGHT$ function). 4 SpanIncluding Extracts the characters from the string, which are in the given character set. 5 SpanExcluding Extracts the characters from the string which are not in the given character set. Here is a list of Conversion Methods. Sr.No. Method & Description 1 MakeUpper Converts all the characters in this string to uppercase characters. 2 MakeLower Converts all the characters in this string to lowercase characters. 3 MakeReverse Reverses the characters in this string. 4 Format Format the string as sprintf does. 5 TrimLeft Trim leading white-space characters from the string. 6 TrimRight Trim trailing white-space characters from the string. Here is a list of Searching Methods. Sr.No. Method & Description 1 Find Finds a character or substring inside a larger string. 2 ReverseFind Finds a character inside a larger string; starts from the end. 3 FindOneOf Finds the first matching character from a set. Here is a list of Buffer Access Methods. Sr.No. Method & Description 1 GetBuffer Returns a pointer to the characters in the CString. 2 GetBufferSetLength Returns a pointer to the characters in the CString, truncating to the specified length. 3 ReleaseBuffer Releases control of the buffer returned by GetBuffer 4 FreeExtra Removes any overhead of this string object by freeing any extra memory previously allocated to the string. 5 LockBuffer Disables reference counting and protects the string in the buffer. 6 UnlockBuffer Enables reference counting and releases the string in the buffer. Here is a list of Windows-Specific Methods. Sr.No. Method & Description 1 AllocSysString Allocates a BSTR from CString data. 2 SetSysString Sets an existing BSTR object with data from a CString object. 3 LoadString Loads an existing CString object from a Windows CE resource. Following are the different operations on CString objects − Create String You can create a string by either using a string literal or creating an instance of CString class. BOOL CMFCStringDemoDlg::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 CString string1 = _T(“This is a string1”); CString string2(“This is a string2″); m_strText.Append(string1 + L”n”); m_strText.Append(string2); 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. Empty String You can create an empty string by either using an empty string literal or by using CString::Empty() method. You can also check whether a string is empty or not using Boolean property isEmpty. BOOL CMFCStringDemoDlg::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 CString string1 = _T(“”); CString string2; string2.Empty(); if(string1.IsEmpty()) m_strText.Append(L”String1 is emptyn”); else m_strText.Append(string1 + L”n”); if(string2.IsEmpty()) m_strText.Append(L”String2 is empty”); else m_strText.Append(string2); 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. String Concatenation To concatenate two or more strings, you can use + operator to concatenate two strings or a CString::Append() method. BOOL CMFCStringDemoDlg::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 //To concatenate two CString objects CString s1 = _T(“This “); // Cascading concatenation s1 += _T(“is a “); CString s2 = _T(“test”); CString message = s1; message.Append(_T(“big “) + s2); // Message contains “This is a big test”. m_strText = L”message: ” + message; 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. String Length To find the length of the string you can use the CString::GetLength() method, which returns the number of characters in
MFC – Discussion
Discuss MFC ”; Previous Next 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. Print Page Previous Next Advertisements ”;
MFC – Useful Resources
MFC – Useful Resources ”; Previous Next The following resources contain additional information on MFC. Please use them to get more in-depth knowledge on this. Useful Links on MFC MFC Wiki – Wikipedia Reference for MFC. Useful Books on MFC To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;
MFC – Windows Fundamentals
MFC – Windows Fundamentals ”; Previous Next In this chapter, we will be covering the fundamentals of Windows. To create a program, also called an application, you derive a class from the MFC”s CWinApp. CWinApp stands for Class for a Windows Application. 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 the project name ‘MFCWindowDemo’ in the Name field and click OK to continue. You will see the following dialog box. Step 6 − Click Next. Step 7 − Select the options as shown in the dialog box given above and click Finish. Step 8 − An empty project is created. Step 9 − To make it an 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. Window Creation Any application has two main sections − Class Frame or Window Let us create a window using the following steps − Step 1 − To create an application, we need to derive a class from the MFC”s CWinApp. #include class CExample : public CWinApp { BOOL InitInstance() { return TRUE; } }; Step 2 − We also need a frame/window to show the content of our application. Step 3 − For this, we need to add another class and derive it from the MFC”s CFrameWnd class and implement its constructor and a call the Create() method, which will create a frame/window as shown in the following code. class CMyFrame : public CFrameWnd { public: CMyFrame() { Create(NULL, _T(“MFC Application Tutorial”)); } }; Step 4 − As you can see that Create() method needs two parameters, the name of the class, which should be passed as NULL, and the name of the window, which is the string that will be shown on the title bar. Main Window After creating a window, to let the application use it, you can use a pointer to show the class used to create the window. In this case, the pointer would be CFrameWnd. To use the frame window, assign its pointer to the CWinThread::m_pMainWnd member variable. This is done in the InitInstance() implementation of your application. Step 1 − Here is the implementation of InitInstance() in CExample class. class CExample : public CWinApp { BOOL InitInstance() { CMyFrame *Frame = new CMyFrame(); m_pMainWnd = Frame; Frame->ShowWindow(SW_NORMAL); Frame->UpdateWindow(); return TRUE; } }; Step 2 − Following is the complete implementation of Example.cpp file. #include <afxwin.h> class CMyFrame : public CFrameWnd { public: CMyFrame() { Create(NULL, _T(“MFC Application Tutorial”)); } }; class CExample : public CWinApp { BOOL InitInstance() { CMyFrame *Frame = new CMyFrame(); m_pMainWnd = Frame; Frame->ShowWindow(SW_NORMAL); Frame->UpdateWindow(); return TRUE; } }; CExample theApp; Step 3 − When we run the above application, the following window is created. Windows Styles Windows styles are characteristics that control features such as window appearance, borders, minimized or maximized state, or other resizing states, etc. Following is a list of styles which you can use while creating a Window. Sr.No. Style & Description 1 WS_BORDER Creates a window that has a border. 2 WS_CAPTION Creates a window that has a title bar (implies the WS_BORDER style). Cannot be used with the WS_DLGFRAME style. 3 WS_CHILD Creates a child window. Cannot be used with the WS_POPUP style. 4 WS_CHILDWINDOW Same as the WS_CHILD style. 5 WS_CLIPCHILDREN Excludes the area occupied by child windows when you draw within the parent window. Used when you create the parent window. 6 WS_CLIPSIBLINGS Clips child windows relative to each other; that is, when a particular child window receives a paint message, the WS_CLIPSIBLINGS style clips all other overlapped child windows out of the region of the child window to be updated. (If WS_CLIPSIBLINGS is not given and child windows overlap, when you draw within the client area of a child window, it is possible to draw within the client area of a neighboring child window.) For use with the WS_CHILD style only. 7 WS_DISABLED Creates a window that is initially disabled. 8 WS_DLGFRAME Creates a window with a double border but no title. 9 WS_GROUP Specifies the first control of a group of controls in which the user can move from one control to the next with the arrow keys. All controls defined with the WS_GROUP style FALSE after the first control belong to the same group. The next control with the WS_GROUP style starts the next group (that is, one group ends where the next begins). 10 WS_HSCROLL Creates a window that has a horizontal scroll bar. 11 WS_ICONIC Creates a window that is initially minimized. Same as the WS_MINIMIZE style. 12 WS_MAXIMIZE Creates a window of maximum size. 13 WS_MAXIMIZEBOX Creates a window that has a Maximize button. 14 WS_MINIMIZE Creates a window that is initially minimized. For use with the WS_OVERLAPPED style only. 15 WS_MINIMIZEBOX Creates a window that has a Minimize button. 16 WS_OVERLAPPED Creates an overlapped window. An overlapped window usually has a caption and a border. 17 WS_OVERLAPPED WINDOW Creates an overlapped window with the WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles. 18 WS_POPUP Creates a pop-up window. Cannot be used with the WS_CHILD style. 19 WS_POPUPWINDOW Creates a pop-up window with the WS_BORDER, WS_POPUP, and WS_SYSMENU styles. The WS_CAPTION style must be combined with the WS_POPUPWINDOW style to
MFC – Carray
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
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 – Quick Guide
MFC – Quick Guide ”; Previous Next MFC – Overview 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. Prerequisites We have assumed that you know the following − A little about programming for Windows. The basics of programming in C++. Understand the fundamentals of object-oriented programming. What is MFC? The Microsoft Foundation Class Library (MFC) is an “application framework” for programming in Microsoft Windows. MFC provides much of the code, which are required for the following − Managing Windows. Menus and dialog boxes. Performing basic input/output. Storing collections of data objects, etc. You can easily extend or override the basic functionality the MFC framework in you C++ applications by adding your application-specific code into MFC framework. MFC Framework The MFC framework provides a set of reusable classes designed to simplify Windows programming. MFC provides classes for many basic objects, such as strings, files, and collections that are used in everyday programming. It also provides classes for common Windows APIs and data structures, such as windows, controls, and device contexts. The framework also provides a solid foundation for more advanced features, such as ActiveX and document view processing. In addition, MFC provides an application framework, including the classes that make up the application architecture hierarchy. Why MFC? The MFC framework is a powerful approach that lets you build upon the work of expert programmers for Windows. MFC framework has the following advantages. It shortens development time. It makes code more portable. It also provides tremendous support without reducing programming freedom and flexibility. It gives easy access to “hard to program” user-interface elements and technologies. MFC simplifies database programming through Data Access Objects (DAO) and Open Database Connectivity (ODBC), and network programming through Windows Sockets. MFC – Environment Setup Microsoft Visual C++ is a programming environment used to create applications for the Microsoft Windows operating systems. To use MFC framework in your C++ application, you must have installed either Microsoft Visual C++ or Microsoft Visual Studio. Microsoft Visual Studio also contains the Microsoft Visual C++ environment. Microsoft provides a free version of visual studio which also contains SQL Server and it can be downloaded from https://www.visualstudio.com/en-us/downloads/downloadvisual- studio-vs.aspx. Following are the installation steps. Step 1 − Once Visual Studio is downloaded, run the installer. The following dialog box will be displayed. Step 2 − Click Install to start the installation process. Step 3 − Once Visual Studio is installed successfully, you will see the following dialog box. Step 4 − Close this dialog box and restart your computer if required. Step 5 − Open Visual studio from the Start menu, which will open the following dialog box. It will take some time for preparation, while starting for the first time. Step 6 − Next, you will see the main window of Visual Studio. Step 7 − You are now ready to start your application. MFC – VC++ Projects 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. MFC – Getting Started 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
MFC – Standard I/O
MFC – Standard I/O ”; Previous Next The MFC library provides its own version of file processing. This is done through a class named CStdioFile. The CStdioFile class is derived from CFile. It can handle the reading and writing of Unicode text files as well as ordinary multi-byte text files. Here is the list of constructors, which can initialize a CStdioFile object − CStdioFile(); CStdioFile(CAtlTransactionManager* pTM); CStdioFile(FILE* pOpenStream); CStdioFile(LPCTSTR lpszFileName, UINT nOpenFlags); CStdioFile(LPCTSTR lpszFileName, UINT nOpenFlags, CAtlTransactionManager* pTM); Here is the list of methods in CStdioFile − Sr.No. Name & Description 1 Open Overloaded. Open is designed for use with the default CStdioFile constructor (Overrides CFile::Open). 2 ReadString Reads a single line of text. 3 Seek Positions the current file pointer. 4 WriteString Writes a single line of text. Let us look into a simple example again by creating a new MFC dialog based application. Step 1 − Drag one edit control and two buttons as shown in the following snapshot. Step 2 − Add value variable m_strEditCtrl for edit control. Step 3 − Add click event handler for Open and Save buttons. Step 4 − Here is the implementation of event handlers. void CMFCStandardIODlg::OnBnClickedButtonOpen() { // TODO: Add your control notification handler code here UpdateData(TRUE); CStdioFile file; file.Open(L”D:\MFCDirectoryDEMO\test.txt”, CFile::modeRead | CFile::typeText); file.ReadString(m_strEditCtrl); file.Close(); UpdateData(FALSE); } void CMFCStandardIODlg::OnBnClickedButtonSave() { // TODO: Add your control notification handler code here UpdateData(TRUE); CStdioFile file; if (m_strEditCtrl.GetLength() == 0) { AfxMessageBox(L”You must specify the text.”); return; } file.Open(L”D:\MFCDirectoryDEMO\test.txt”, CFile::modeCreate | CFile::modeWrite | CFile::typeText); file.WriteString(m_strEditCtrl); file.Close(); } Step 5 − When the above code is compiled and executed, you will see the following output. Step 6 − Write something and click Save. It will save the data in *.txt file. Step 7 − If you look at the location of the file, you will see that it contains the test.txt file. Step 8 − Now, close the application. Run the same application. When you click Open, the same text loads again. Step 9 − It starts by opening the file, reading the file, followed by updating the Edit Control. Print Page Previous Next Advertisements ”;
MFC – Libraries
MFC – Libraries ”; Previous Next A library is a group of functions, classes, or other resources that can be made available to programs that need already implemented entities without the need to know how these functions, classes, or resources were created or how they function. A library makes it easy for a programmer to use functions, classes, and resources etc. created by another person or company and trust that this external source is reliable and efficient. Some unique features related to libraries are − A library is created and functions like a normal regular program, using functions or other resources and communicating with other programs. To implement its functionality, a library contains functions that other programs would need to complete their functionality. At the same time, a library may use some functions that other programs would not need. The program that uses the library, are also called the clients of the library. There are two types of functions you will create or include in your libraries − An internal function is one used only by the library itself and clients of the library will not need access to these functions. External functions are those that can be accessed by the clients of the library. There are two broad categories of libraries you will deal with in your programs − Static libraries Dynamic libraries Static Library A static library is a file that contains functions, classes, or resources that an external program can use to complement its functionality. To use a library, the programmer has to create a link to it. The project can be a console application, a Win32 or an MFC application. The library file has the lib extension. Step 1 − Let us look into a simple example of static library by creating a new Win32 Project. Step 2 − On Application Wizard dialog box, choose the Static Library option. Step 3 − Click Finish to continue. Step 4 − Right-click on the project in solution explorer and add a header file from Add → New Item…menu option. Step 5 − Enter Calculator.h in the Name field and click Add. Add the following code in the header file − #pragma once #ifndef _CALCULATOR_H_ #define _CALCULATOR_H_ double Min(const double *Numbers, const int Count); double Max(const double *Numbers, const int Count); double Sum(const double *Numbers, const int Count); double Average(const double *Numbers, const int Count); long GreatestCommonDivisor(long Nbr1, long Nbr2); #endif // _CALCULATOR_H_ Step 6 − Add a source (*.cpp) file in the project. Step 7 − Enter Calculator.cpp in the Name field and click Add. Step 8 − Add the following code in the *.cpp file − #include “StdAfx.h” #include “Calculator.h” double Min(const double *Nbr, const int Total) { double Minimum = Nbr[0]; for (int i = 0; i < Total; i++) if (Minimum > Nbr[i]) Minimum = Nbr[i]; return Minimum; } double Max(const double *Nbr, const int Total) { double Maximum = Nbr[0]; for (int i = 0; i < Total; i++) if (Maximum < Nbr[i]) Maximum = Nbr[i]; return Maximum; } double Sum(const double *Nbr, const int Total) { double S = 0; for (int i = 0; i < Total; i++) S += Nbr[i]; return S; } double Average(const double *Nbr, const int Total) { double avg, S = 0; for (int i = 0; i < Total; i++) S += Nbr[i]; avg = S / Total; return avg; } long GreatestCommonDivisor(long Nbr1, long Nbr2) { while (true) { Nbr1 = Nbr1 % Nbr2; if (Nbr1 == 0) return Nbr2; Nbr2 = Nbr2 % Nbr1; if (Nbr2 == 0) return Nbr1; } } Step 9 − Build this library from the main menu, by clicking Build → Build MFCLib. Step 10 − When library is built successfully, it will display the above message. Step 11 − To use these functions from the library, let us add another MFC dialog application based from File → New → Project. Step 12 − Go to the MFCLibDebug folder and copy the header file and *.lib files to the MFCLibTest project as shown in the following snapshot. Step 13 − To add the library to the current project, on the main menu, click Project → Add Existing Item and select MFCLib.lib. Step 14 − Design your dialog box as shown in the following snapshot. Step 15 − Add value variable for both edit controls of value type double. Step 16 − Add value variable for Static text control, which is at the end of the dialog box. Step 17 − Add the event handler for Calculate button. To add functionality from the library, we need to include the header file in CMFCLibTestDlg.cpp file. #include “stdafx.h” #include “MFCLibTest.h” #include “MFCLibTestDlg.h” #include “afxdialogex.h” #include “Calculator.h” Step 18 − Here is the implementation of button event handler. void CMFCLibTestDlg::OnBnClickedButtonCal() { // TODO: Add your control notification handler code here UpdateData(TRUE); CString strTemp; double numbers[2]; numbers[0] = m_Num1; numbers[1] = m_Num2; strTemp.Format(L”%.2f”, Max(numbers,2)); m_strText.Append(L”Max is:t” + strTemp); strTemp.Format(L”%.2f”, Min(numbers, 2)); m_strText.Append(L”nMin is:t” + strTemp); strTemp.Format(L”%.2f”, Sum(numbers, 2)); m_strText.Append(L”nSum is:t” + strTemp); strTemp.Format(L”%.2f”, Average(numbers, 2)); m_strText.Append(L”nAverage is:t” + strTemp); strTemp.Format(L”%d”, GreatestCommonDivisor(m_Num1, m_Num2)); m_strText.Append(L”nGDC is:t” + strTemp); UpdateData(FALSE); } Step 19 − When the above code is compiled and executed, you will see the following output. Step 20 − Enter two values in the edit field and click Calculate. You will now see the result after calculating from the library. Dynamic Library A Win32 DLL is a library that can be made available to programs that run on a Microsoft Windows computer. As a normal library, it is made of functions and/or other resources grouped in a file. The DLL abbreviation stands for Dynamic Link Library. This means that, as opposed to a static library, a DLL allows the programmer to decide on when and how other applications will be linked to this type of library. For example, a DLL allows difference applications to use its library as they see fit and as necessary. In fact, applications created on different programming