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 ”;

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 ”;