Click here to Skip to main content
Click here to Skip to main content

Creating and Using custom controls in VC++

By , 21 Sep 2003
 

Sample Image - CustomControl.gif

Introduction

Hi there! This is my fourth article for The Code Project. Migrating towards the VC++, I have firstly concerned with the custom controls that can be created with the help of VC++, since that is a very helpful feature when you want to modify the contents of any control or you want to create your own. So, I have decided to write this article so the new developers or the beginners who want to develop any controls will get some help from my small knowledge.

Now, that’s all for the introduction now, I am moving towards the original point of view: that is, how and why to create any custom control. As I have interest in developing applications in Win32 API because of its small size and stand alone executables, I never ever had worked on the VC++ but, it is too much powerful language and the power-features in it have attracted me towards it. One of them is the custom control. Too much of articles on the CodeProject have used the custom controls. But when I have read them firstly, I haven’t understood how to create and get the messages and then process on that messages in the simple Windows applications. The custom controls give the developer a convenient way to create the control and visualize that as the regular control.

(As I am a beginner with VC++, please tell me if there are any mistakes in this article).

Where is it?

Now, the question is that, where is the custom control? So, answer is below. The picture below shows the custom control, it lies in the control bar.

The picture shows the position of the custom control. You are able to select it and draw directly on your form resource.

The main problem arises after you have put that control on your form that if you build and execute the program the view is not available since you haven't selected any class for your control, so that part is discussed in a later section.

Creating a Class

Now, the figure above shows the custom control as drawn on the form view. Now, you have to right click on that and select ClassWizard form the popup menu.

Selecting a class

After you have clicked the Class wizard, the dialog shown here appears on the screen. From it, select Add Class and then New.

Now, once you have clicked the New button, the dialog to select the base class for our custom control will appear as below. Here, you have multiple choices to select any base class. That means you can customize the basic control like, static control or the edit control, by adding the new features, or you are able to create a fully new control. I have decided to create a fully new control like a pad, and so, I have selected a basic CWnd class as a base class.

And finally, you have created a class for your control. Now, the serious part begins....

As the class has been created by using the CWnd as a base, we will have to register this class since this is a custom class. So, we will have to write the function RegisterWndClass() to do that. It may be coded as below...

BOOL MyCustomControl::RegisterWndClass()
{
    WNDCLASS windowclass;
    HINSTANCE hInst = AfxGetInstanceHandle();

    //Check weather the class is registerd already
    if (!(::GetClassInfo(hInst, MYWNDCLASS, &windowclass)))
    {
        //If not then we have to register the new class
        windowclass.style = CS_DBLCLKS;// | CS_HREDRAW | CS_VREDRAW;
        windowclass.lpfnWndProc = ::DefWindowProc;
        windowclass.cbClsExtra = windowclass.cbWndExtra = 0;
        windowclass.hInstance = hInst;
        windowclass.hIcon = NULL;
        windowclass.hCursor = AfxGetApp()->LoadStandardCursor(IDC_ARROW);
        windowclass.hbrBackground = ::GetSysColorBrush(COLOR_WINDOW);
        windowclass.lpszMenuName = NULL;
        windowclass.lpszClassName = MYWNDCLASS;

        if (!AfxRegisterClass(&windowclass))
        {
            AfxThrowResourceException();
            return FALSE;
        }
    }

    return TRUE;
}

In this way, we have registered the new window class. Now, you will have to add that function in your default class constructor as follows:

MyCustomControl::MyCustomControl()
{
    //Register My window class
    RegisterWndClass();
}

I think anyone will think what is MYWNDCLASS. The answer is that it is the defined class name for our custom class. It is defined at the top of the MyCustomControl.h file as follows:

#define MYWNDCLASS "MyDrawPad"

Now, we have our own class called MyDrawPad.

Attaching Class to the Custom Control:

With all things going right, we are approaching towards completing the creation of the custom control. The last thing remaining is to set the custom control as our created window class. For that, right click on the custom control in the resource view and then select the properties of the custom control. The dialog box will appear as shown below...

Then, set the class name as MyDrawPad that we have created earlier. Here you can select the window style by changing the hexadecimal value in the style edit box.

I have experimented with some of the values, you can also try them.

Doing the DataExchange

Now, all the things are set up. But the data must be exchanged between the window and our application. So, add a variable for our custom control to your dialog class as follows:

// Implementation
protected:
HICON m_hIcon;
MyCustomControl m_drawpad;//This is our custom control

After that, you have to add the following code in the DoDataExchage() function to interact with the custom control.

void CCustomControlDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    //{{AFX_DATA_MAP(CCustomControlDlg)
    // NOTE: the ClassWizard will add DDX and DDV calls here
    DDX_Control(pDX,IDC_CUSTOM1,m_drawpad);
    //}}AFX_DATA_MAP
}

Now, are you ready for the action??? Then, press Ctrl+F5 to compile and execute the program. (Wish you all the best... I think there is no error!!!)

Do not forget to write #include "MyCustomControl.h" in the Dialog's Header file, else it will generate too many errors. (I Think you will not blame me HHAA HHAA HHAA).

Adding and processing the messages

After succeeding in the critical part above, you should get the Dialog box containing the white rectangle on it. That is our custom control (Belive Me!). That's only a small window. Now, we will have to add some Windows messages to interact with that control. Read carefully...

To add Windows messages to the window, right click on the class MyCustomControl and select Add Windows Message Handler to add the messages like, mouse move, click etc...

In this way, after a long work (is it?), you have created your own custom control. Now relax, and start writing your own. And please rate my article (I like it). For example, I have written a simple DrawPad in the included source code.

Now, we will go through a short summary of this article:

To create the custom control, we will have to do the following things:

  • Create a simple MFC Application containing Dialog resource.
  • Select the custom control form the control bar.
  • Draw the custom control on the Dialog resource.
  • Right click the custom control and select the Class Wizard.
  • From Add class popup, add new custom class selecting the appropriate base class.
  • Add the code and register the Custom Window class.
  • Add the member variable for a base class (custom class) in the dialog.
  • Set the custom control's class to the registered window class name.
  • Add the DoDataExchange code.
  • Now, press Ctrl+F5 to compile and execute the application.
  • Add/Edit the Windows message handlers by right clicking the Custom control's class in the class view.

If you really like it, then mail me at yogmj@hotmail.com, and mail me your suggestions and spelling Missssstakes in this article. Also any bugs in the source code (as I am the BugHunter{ I think so, Do you?}).

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Yogesh M Joshi.
Software Developer AVAYA India Pvt Ltd.
India India
Member
I have completed my B.E. Degree in IT form Aditya Engineering College, Beed. (Maharashtra) India.
 
I have completed Diploma In Advanced Computing (DAC) in Feb 07.
 
Now I am working for AVAYA India Pvt. LTD as software engineer.
Platform : C/C++, Solaris 10, AIX and Windows

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questioncreating more than 2 Edit control and one button in Custom controlmemberNANA@12330 Apr '13 - 1:27 
GeneralMy vote of 5memberpeoria12318 Jul '12 - 4:58 
QuestionThis Article is so Greatmembergeolxy4 Jan '12 - 1:44 
GeneralMy vote of 5membersmartcrypto27 Sep '11 - 2:58 
NewsWM_GETDLGCODE - keyboard input / navigationmemberPandele Florin27 May '11 - 2:07 
GeneralMy vote of 4membermouneshremo13 Mar '11 - 21:40 
GeneralMy vote of 5memberpratikmota20 Jul '10 - 22:49 
QuestionHow to develop DLL for class which is used for custom controlmembergsheladia7 Jun '09 - 20:04 
Generalre:memberStephen_God5 Mar '09 - 15:15 
GeneralAn Very Good Article For A BeginnermemberLi Shu23 Oct '08 - 16:33 
Generalgoodmember76717 Sep '08 - 23:23 
Question"MyDrawPad"??memberRoyman7 May '07 - 19:38 
GeneralProblem handling - when something goes wrongmemberMoak2 May '07 - 4:14 
QuestionHow to add a custom class using class wizardmembersmartgraviton14 Sep '06 - 2:39 
QuestionMac Address controlmemberPlennguyen8 Aug '06 - 17:38 
GeneralNice work... [modified]memberctroyp29 Jul '06 - 19:15 
QuestionHow to generate Drive control in VC++memberLalit Kandi10 Jul '06 - 21:36 
GeneralUsing againt that controlmembermcnam2 Jun '06 - 9:41 
GeneralGood jobmembernprogrammer6 Feb '06 - 11:16 
GeneralAppreciatemembermohanrajh12 Jan '06 - 23:15 
GeneralRe: AppreciatememberYogesh M Joshi.22 Jan '06 - 21:11 
GeneralGeneral functionmemberAslFunky14 Dec '04 - 2:36 
GeneralRe: General functionmemberYogesh M Joshi.7 Jan '05 - 7:32 
GeneralHelp: To generate Drive control in VC++memberLalit Kandi10 Jul '06 - 21:33 
GeneralExcellentmemberkobuster19 Sep '04 - 16:25 
GeneralRe: ExcellentmemberYogesh M Joshi.5 Feb '05 - 5:28 
GeneralOnCreatememberZejulioZ7 Sep '04 - 21:43 
GeneralRe: OnCreatesussAnonymous12 Feb '05 - 1:56 
GeneralGood job...membermanthrax22 Mar '04 - 15:09 
GeneralRe: Good job...memberYogesh M Joshi.12 May '04 - 22:02 
GeneralGood effort but...memberPaul S. Vickery22 Sep '03 - 22:37 
GeneralRe: Good effort but...memberSoothingMist(Peter)11 Feb '04 - 9:29 
GeneralRe: Good effort but...memberYogesh M Joshi.12 May '04 - 22:00 
GeneralPlayBoy.com!sussAnonymous22 Sep '03 - 7:53 
GeneralRe: PlayBoy.com!memberJuan Carlos Cobas22 Sep '03 - 10:22 
GeneralRe: PlayBoy.com!sussAnonymous22 Sep '03 - 11:18 
GeneralRe: PlayBoy.com!memberLars [Large] Werner23 Sep '03 - 20:56 
GeneralRe: PlayBoy.com!memberfjosesen25 Sep '03 - 20:19 
GeneralRe: PlayBoy.com!memberWildWildWind12 Mar '05 - 6:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 22 Sep 2003
Article Copyright 2003 by Yogesh M Joshi.
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid