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 ”;
Category: mfc
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 – Messages & Events
MFC – Messages & Events ”; Previous Next An application is made of various objects. Most of the time, more than one application is running on the computer and the operating system is constantly asked to perform some assignments. Because there can be so many requests presented unpredictably, the operating system leaves it up to the objects to specify what they want, when they want it, and what behavior or result they expect. Overview The Microsoft Windows operating system cannot predict what kinds of requests one object would need to be taken care of and what type of assignment another object would need. To manage all these assignments and requests, the objects send messages. Each object has the responsibility to decided what message to send and when. In order to send a message, a control must create an event. To make a distinction between the two, a message”s name usually starts with WM_ which stands for Window Message. The name of an event usually starts with On which indicates an action. The event is the action of sending the message. Map of Messages Since Windows is a message-oriented operating system, a large portion of programming for the Windows environment involves message handling. Each time an event such as a keystroke or mouse click occurs, a message is sent to the application, which must then handle the event. For the compiler to manage messages, they should be included in the class definition. The DECLARE_MESSAGE_MAP macro should be provided at the end of the class definition as shown in the following code. class CMainFrame : public CFrameWnd { public: CMainFrame(); protected: DECLARE_MESSAGE_MAP() }; The actual messages should be listed just above the DECLARE_MESSAGE_MAP line. To implement the messages, you need to create a table of messages that your program is using. This table uses two delimiting macros; Its starts with a BEGIN_MESSAGE_MAP and ends with an END_MESSAGE_MAP macros. The BEGIN_MESSAGE_MAP macro takes two arguments, the name of your class and the MFC class you derived your class from as shown in the following code. #include <afxwin.h> class CMainFrame : public CFrameWnd { public: CMainFrame(); protected: DECLARE_MESSAGE_MAP() }; CMainFrame::CMainFrame() { // Create the window”s frame Create(NULL, L”MFC Messages Demo”, WS_OVERLAPPEDWINDOW, CRect(120, 100, 700, 480), NULL); } class CMessagesApp : public CWinApp { public: BOOL InitInstance(); }; BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) END_MESSAGE_MAP() BOOL CMessagesApp::InitInstance(){ m_pMainWnd = new CMainFrame; m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); return TRUE; } CMessagesApp theApp; Let us look into a simple example by creating a new Win32 project. Step 1 − To create an MFC project, right-click on the project and select Properties. Step 2 − In the left section, click Configuration Properties → General. Step 3 − Select the ‘Use MFC in Shared DLL’ option in Project Defaults section and click OK. Step 4 − We need to add a new source file. Step 5 − Right-click on your Project and select Add → New Item. Step 6 − In the Templates section, click C++ File (.cpp). Step 7 − Click Add to Continue. Step 8 − Now, add the following code in the *.cpp file. #include <afxwin.h> class CMainFrame : public CFrameWnd { public: CMainFrame(); protected: DECLARE_MESSAGE_MAP() }; CMainFrame::CMainFrame() { // Create the window”s frame Create(NULL, L”MFC Messages Demo”, WS_OVERLAPPEDWINDOW, CRect(120, 100, 700, 480), NULL); } class CMessagesApp : public CWinApp { public: BOOL InitInstance(); }; BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) END_MESSAGE_MAP() BOOL CMessagesApp::InitInstance() { m_pMainWnd = new CMainFrame; m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); return TRUE; } CMessagesApp theApp; Windows Messages There are different types of Windows messages like creating a window, showing a window etc. Here are some of the commonly used windows messages. Given below are the different types of Window messages. Message Map entry Description WM_ACTIVATE ON_WM_ACTIVATE() The framework calls this member function when a CWnd object is being activated or deactivated. WM_ACTIVATEA PP ON_WM_ACTIVATEAPP() The framework calls this member function to all top-level windows of the task being activated and for all top-level windows of the task being deactivated. WM_APPCOMM AND ON_WM_APPCOMMAND() The framework calls this member function when the user generates an application command event. WM_CANCELMODE WM_CANCELMODE() The framework calls this member function to inform CWnd to cancel any internal mode. WM_CHILDACTIVATE ON_WM_CHILDACTIVATE() If the CWnd object is a multiple document interface (MDI) child window, OnChildActivate is called by the framework when the user clicks the window”s title bar or when the window is activated, moved, or sized. WM_CLIPBOAR DUPDATE ON_WM_CLIPBOARDUPDATE() The framework calls this member function when the contents of the clipboard have changed. WM_CLOSE ON_WM_CLOSE() The framework calls this member function as a signal that the CWnd or an application is to terminate. WM_CONTEXTMENU ON_WM_CONTEXTMENU() Called by the framework when the user has clicked the right mouse button (rightclicked) in the window. WM_COPYDATA ON_WM_COPYDATA() This member function is called by the framework to copy data from one application to another. WM_CREATE ON_WM_CREATE() The framework calls this member function when an application requests that the Windows window be created by calling the Create or CreateEx member function. WM_CTLCOLOR ON_WM_CTLCOLOR() The framework calls this member function when a child control is about to be drawn. WM_DELETEITEM ON_WM_DELETEITEM() The framework calls this member function to inform the owner of an owner-draw list box or combo box that the list box or combo box is destroyed or that items have been removed. WM_DESTROY ON_WM_DESTROY() he framework calls this member function to inform the CWnd object that it is being destroyed. WM_DRAWITEM ON_WM_DRAWITEM() The framework calls this member function for the owner of an owner-draw button control, combo-box control, list-box control, or menu when a visual aspect of the control or menu has changed. WM_DROPFILES ON_WM_DROPFILES() The framework calls this member function when the user releases the left mouse button over a window that has registered itself as the recipient of dropped files. WM_ENABLE ON_WM_ENABLE() The framework calls this member function when an application changes the enabled state of the CWnd object. Syntax. WM_HELPINFO ON_WM_HELPINFO() Handles F1 Help within the application (using the current context). WM_HOTKEY ON_WM_HOTKEY() The framework calls this member function when
MFC – Database Classes
MFC – Database Classes ”; Previous Next A database is a collection of information that is organized so that it can easily be accessed, managed, and updated. The MFC database classes based on ODBC are designed to provide access to any database for which an ODBC driver is available. Because the classes use ODBC, your application can access data in many different data formats and different local/remote configurations. You do not have to write special-case code to handle different database management systems (DBMSs). As long as your users have an appropriate ODBC driver for the data they want to access, they can use your program to manipulate data in tables stored there. A data source is a specific instance of data hosted by some database management system (DBMS). Examples include Microsoft SQL Server, Microsoft Access, etc. CDatabase MFC provides a class CDatabase which represents a connection to a data source, through which you can operate on the data source. You can have one or more CDatabase objects active at a time in your application. Here is the list of methods in CDatabase class. Sr.No. Name & Description 1 BeginTrans Starts a “transaction” — a series of reversible calls to the AddNew, Edit, Delete, and Update member functions of class CRecordset — on the connected data source. The data source must support transactions for BeginTrans to have any effect. 2 BindParameters Allows you to bind parameters before calling ExecuteSQL. 3 Cancel Cancels an asynchronous operation or a process from a second thread. 4 CanTransact Returns nonzero if the data source supports transactions. 5 CanUpdate Returns nonzero if the CDatabase object is updatable (not read-only). 6 Close Closes the data source connection. 7 CommitTrans Completes a transaction begun by BeginTrans. Commands in the transaction that alter the data source are carried out. 8 ExecuteSQL Executes a SQL statement. No data records are returned. 9 GetBookmarkPersistence Identifies the operations through which bookmarks persist on recordset objects. 10 GetConnect Returns the ODBC connection string used to connect the CDatabase object to a data source. 11 GetCursorCommitBehavior Identifies the effect of committing a transaction on an open recordset object. 12 GetCursorRollbackBehavior Identifies the effect of rolling back a transaction on an open recordset object. 13 GetDatabaseName Returns the name of the database currently in use. 14 IsOpen Returns nonzero if the CDatabase object is currently connected to a data source. 15 OnSetOptions Called by the framework to set standard connection options. The default implementation sets the query timeout value. You can establish these options ahead of time by calling SetQueryTimeout. 16 Open Establishes a connection to a data source (through an ODBC driver). 17 OpenEx Establishes a connection to a data source (through an ODBC driver). 18 Rollback Reverses changes made during the current transaction. The data source returns to its previous state, as defined at the BeginTrans call, unaltered. 19 SetLoginTimeout Sets the number of seconds after which a data source connection attempt will time out. 20 SetQueryTimeout Sets the number of seconds after which database query operations will time out. Affects all subsequent recordset Open, AddNew, Edit, and Delete calls. Let us look into a simple example by creating a new MFC dialog based application. Step 1 − Change the caption of TODO line to Retrieve Data from Database and drag one button and one List control as shown in the following snapshot. Step 2 − Add click event handler for button and control variable m_ListControl for List Control. Step 3 − We have simple database which contains one Employees table with some records as shown in the following snapshot. Step 4 − We need to include the following headers file so that we can use CDatabase class. #include “odbcinst.h” #include “afxdb.h” Insert Query The SQL INSERT INTO Statement is used to add new rows of data to a table in the database. Step 1 − To add new records, we will use the ExecuteSQL() function of CDatabase class as shown in the following code. CDatabase database; CString SqlString; CString strID, strName, strAge; CString sDriver = L”MICROSOFT ACCESS DRIVER (*.mdb)”; CString sDsn; CString sFile = L”D:\Test.mdb”; // You must change above path if it”s different int iRec = 0; // Build ODBC connection string sDsn.Format(L”ODBC;DRIVER={%s};DSN=””;DBQ=%s”, sDriver, sFile); TRY { // Open the database database.Open(NULL,false,false,sDsn); SqlString = “INSERT INTO Employees (ID,Name,age) VALUES (5,”Sanjay”,69)”; database.ExecuteSQL(SqlString); // Close the database database.Close(); }CATCH(CDBException, e) { // If a database exception occured, show error msg AfxMessageBox(L”Database error: ” + e→m_strError); } END_CATCH; Step 2 − When the above code is compiled and executed, you will see that a new record is added in your database. Retrieve Record To retrieve the above table in MFC application, we implement the database related operations in the button event handler as shown in the following steps. Step 1 − To use CDatabase, construct a CDatabase object and call its Open() function. This will open the connection. Step 2 − Construct CRecordset objects for operating on the connected data source, pass the recordset constructor a pointer to your CDatabase object. Step 3 − After using the connection, call the Close function and destroy the CDatabase object. void CMFCDatabaseDemoDlg::OnBnClickedButtonRead() { // TODO: Add your control notification handler code here CDatabase database; CString SqlString; CString strID, strName, strAge; CString sDriver = “MICROSOFT ACCESS DRIVER (*.mdb)”; CString sFile = L”D:\Test.mdb”; // You must change above path if it”s different int iRec = 0; // Build ODBC connection string sDsn.Format(“ODBC;DRIVER={%s};DSN=””;DBQ=%s”,sDriver,sFile); TRY { // Open the database database.Open(NULL,false,false,sDsn); // Allocate the recordset CRecordset recset( &database ); // Build the SQL statement SqlString = “SELECT ID, Name, Age ” “FROM Employees”; // Execute the query recset.Open(CRecordset::forwardOnly,SqlString,CRecordset::readOnly); // Reset List control if there is any data ResetListControl(); // populate Grids ListView_SetExtendedListViewStyle(m_ListControl,LVS_EX_GRIDLINES); // Column width and heading m_ListControl.InsertColumn(0,”Emp ID”,LVCFMT_LEFT,-1,0); m_ListControl.InsertColumn(1,”Name”,LVCFMT_LEFT,-1,1); m_ListControl.InsertColumn(2, “Age”, LVCFMT_LEFT, -1, 1); m_ListControl.SetColumnWidth(0, 120); m_ListControl.SetColumnWidth(1, 200); m_ListControl.SetColumnWidth(2, 200); // Loop through each record while( !recset.IsEOF() ) { // Copy each column into a variable recset.GetFieldValue(“ID”,strID); recset.GetFieldValue(“Name”,strName); recset.GetFieldValue(“Age”, strAge); // Insert values into the list
MFC – Overview
MFC – Overview ”; 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. 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. Print Page Previous Next Advertisements ”;