Deriving from Control Classes

Click here to change the theme.

One of the basic techniques of MFC programming to be familiar with is how to create a class derived from a MFC Common Control class, such as CEdit. The most frequent use of this is to override processing of messages, such as a WM_KEYDOWN message.

The following assumes that you already have a dialog box in an existing application.

  • Use ClassWizard to create a new class for your control. In ClassWizard, click on "Add Class", then "New". For the base class, choose the MFC Control class you are deriving from, such as CEdit. If you see a check box called “Add to Component Gallery”, then unless you know how to use the Component Gallery for your own classes, I recommend unchecking the check box. This is not important, but I know the check box is in there somewhere; I just forget where.
  • Include the header file for the derived class where appropriate, such as in your dialog box’s source file.

You then can use the ClassWizard to add processing for messages, such as the WM_KEYDOWN message. Do this using the "Message Maps" tab of the ClassWizard. From there, first ensure that the chosen class name is your derived class, then for the object id, choose your derived class again. Then in the messages list box, choose whatever message you need to override, and then click on "Add Function".

You then can attach a member variable to each control in a dialog box that is the type that you derived from. For example, if you derived from CEdit, then you can process edit boxes using the derived class. Use ClassWizard to attach a member variable to a control. In the Add Member Variable dialog box, finish the variable name and choose “Control” for the category, then for the variable type, choose the class name you used for the derived class. Do this using one of the following two:

  • While in the resource editor with the dialog box open, double-click the control while holding down a control key.
  • Invoke the ClassWizard, then choose your dialog's class (if not already chosen) then go to the "Member Variables" tab. Choose the dialog id for the control, then click on "Add variable".