Visual C++ and MFC Programming 2nd Edition

(Martin Jones) #1

Chapter 12: Dialog-Based Windows Visual C++ and MFC Fundamentals


}

Based on the rules of inheritance and polymorphism, you can also declare the pointer as
CWnd but initialize it with the desired class. Here is an example:

void CParentLoader::TodaysMainEvent()
{
CWnd *Panel = new CStatic;
}

After declaring the variable, you can call the CWnd::Create() method to initialize the
control. The syntax of this method is:

virtual BOOL Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName,
DWORD dwStyle, const RECT& rect, CWnd* pParentWnd,
UINT nID, CCreateContext* pContext = NULL);

To create a fancier control, you can use the CWnd::CreateEx() method.

The availability of a child window to other parts of a program is defined by the scope in
which the control is created. If you create a control in an event or a method of a parent
class, it can be accessed only inside of that event. Trying to access it outside would
produce an error. If you want to access a child or dependent window from more than one
event or method, you must create it globally. This is usually done by declaring the
variable or pointer in the class of the parent.

After declaring the variable, to initialize it, call its Create() method. The syntax of this
method depends on the class you are using to create the window. After initializing the
window, it may become alive, depending on the style or properties you assigned to it.

The other technique you can use is to derive a class from the control whose behavior and
appearance can serve as a foundation for your control. For example, you can derive a
control as follows:

class CColoredLabel : public CStatic
{
public:
CColoredLabel();
virtual ~CColoredLabel();

DECLARE_MESSAGE_MAP()
};

Such a class as the above CColoredLabel gives you access to the public and protected
properties and methods of the base class. To use the new class in your application,
declare a variable from it and call the Create() method.

Practical Learning: Introducing Controls



  1. To create a new application, on the main menu, click File -> New ->Project...

  2. Click MFC Application. Set the application Name as Controls and click OK

  3. Set the Application Type to Dialog Based and click Finish

  4. On the dialog, click the TODO line and press Delete on the keyboard

Free download pdf