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

Creating Custom Controls

By , 11 May 2000
 
  • Download source files - 21 Kb
  • Sample Image - CustomControl.jpg

    Introduction

    In a previous article I demonstrated subclassing a windows common control in order to modify its behaviour or extend its functionality. Sometimes you can only push the windows common controls so far. An example I came across was the common issue of needing a grid control to display and edit tabular data. I subclassed a CListCtrl and extended it to allow subitem editing, multiline cells, sort-on-click headers and a myriad of other features. However, deep down it was still a list control and there came a point where I seemed to be writing more code to stop the control performing actions than I was to actually make it do something.

    I needed to start from scratch, working from a base class that provided only the functionality I needed without any of the features (or liabilities) that I didn't need. Enter the custom control.

    Creating a Custom Control class

    Writing a custom control is very similar to subclassing a windows common control. You derive a new class from an existing class and override the functionality of the base class in order to make it do what you want.

    In this case we'll be deriving a class from CWnd, since this class provides the minimum functionality we need, without too much overhead.

    The first step in creating a custom control is to derive your class from your chosen base class (CWnd). In this example we'll create a custom control for displaying bitmaps, and we'll call this class CBitmapViewer. Obviously there is already the CStatic class that already displays bitmaps, but the example is only meant to demonstrate the possibilities available to the adventurous programmer.

    To your class you should add handlers for the WM_PAINT and WM_ERASEBKGND messages. I've also added an override for PreSubclassWindow in case you wish to perform any initialisation that requires the window to have been created. See my previous article for a discussion of PreSubclassWindow.

    The aim of this control is to display bitmaps, so we'll a method to set the bitmap and call it SetBitmap. We're not only talented, us programmers, but extremely imaginative as well.

    The internal code for the control is unimportant to this discussion but is included for completeness.

    Add a member variable of type CBitmap to the class, as well as the SetBitmap prototype:

    class CBitmapViewer : public CWnd
    {
    // Construction
    public:
        CBitmapViewer();
    
    // Attributes
    public:
        BOOL SetBitmap(UINT nIDResource);
    
        ...
        
    protected:
        CBitmap m_Bitmap;
    };

    In your CBitmapViewer implementation file add the following code for your SetBitmap method, and your WM_PAINT and WM_ERASEBKGND message handlers:

    void CBitmapViewer::OnPaint() 
    {
        // Draw the bitmap - if we have one.
        if (m_Bitmap.GetSafeHandle() != NULL)
        {
            CPaintDC dc(this); // device context for painting
    
            // Create memory DC
            CDC MemDC;
            if (!MemDC.CreateCompatibleDC(&dc))
                return;
    
            // Get Size of Display area
            CRect rect;
            GetClientRect(rect);
    
            // Get size of bitmap
            BITMAP bm;
            m_Bitmap.GetBitmap(&bm);
            
            // Draw the bitmap
            CBitmap* pOldBitmap = (CBitmap*) MemDC.SelectObject(&m_Bitmap);
            dc.StretchBlt(0, 0, rect.Width(), rect.Height(), 
                          &MemDC, 
                          0, 0, bm.bmWidth, bm.bmHeight, 
                          SRCCOPY);
            MemDC.SelectObject(pOldBitmap);      
        }
        
        // Do not call CWnd::OnPaint() for painting messages
    }
    
    BOOL CBitmapViewer::OnEraseBkgnd(CDC* pDC) 
    {
        // If we have an image then don't perform any erasing, since the OnPaint
        // function will simply draw over the background
        if (m_Bitmap.GetSafeHandle() != NULL)
            return TRUE;
        
        // Obviously we don't have a bitmap - let the base class deal with it.
        return CWnd::OnEraseBkgnd(pDC);
    }
    
    BOOL CBitmapViewer::SetBitmap(UINT nIDResource)
    {
        return m_Bitmap.LoadBitmap(nIDResource);
    }
    

    Making the class a Custom Control

    So far we have a class that allows us to load and display a bitmap - but as yet we have no way of actually using this class. We have two choices in creating the control - either dynamically by calling Create or via a dialog template created using the Visual Studio resource editor.

    Since our class is derived from CWnd we can use CWnd::Create to create the control dynamically. For instance, in your dialog's OnInitDialog you could have the following code:

    // CBitmapViewer m_Viewer; - declared in dialog class header
    
    m_Viewer.Create(NULL, _T(""), WS_VISIBLE, CRect(0,0,100,100), this, 1);
    m_Viewer.SetBitmap(IDB_BITMAP1);
    

    where m_Viewer is an object of type CBitmapViewer that is declared in your dialogs header, and IDB_BITMAP1 is the ID of a bitmap resource. The control will be created and the bitmap will display.

    However, what if we wished to place the control in a dialog template using the Visual Studio resource editor? For this we need to register a Windows Class name using the AfxRegisterClass function. Registering a class allows us to specify the background color, the cursor, and the style. See AfxRegisterWndClass in the docs for more information.

    For this example we'll register a simple class and call it "MFCBitmapViewerCtrl". We only need to register the control once, and a neat place to do this is in the constructor of the class we are writing

    #define BITMAPVIEWER_CLASSNAME    _T("MFCBitmapViewerCtrl")  // Window class name
    
    CBitmapViewer::CBitmapViewer()
    {
        RegisterWindowClass();
    }
    
    BOOL CBitmapViewer::RegisterWindowClass()
    {
        WNDCLASS wndcls;
        HINSTANCE hInst = AfxGetInstanceHandle();
    
        if (!(::GetClassInfo(hInst, BITMAPVIEWER_CLASSNAME, &wndcls)))
        {
            // otherwise we need to register a new class
            wndcls.style            = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW;
            wndcls.lpfnWndProc      = ::DefWindowProc;
            wndcls.cbClsExtra       = wndcls.cbWndExtra = 0;
            wndcls.hInstance        = hInst;
            wndcls.hIcon            = NULL;
            wndcls.hCursor          = AfxGetApp()->LoadStandardCursor(IDC_ARROW);
            wndcls.hbrBackground    = (HBRUSH) (COLOR_3DFACE + 1);
            wndcls.lpszMenuName     = NULL;
            wndcls.lpszClassName    = BITMAPVIEWER_CLASSNAME;
    
            if (!AfxRegisterClass(&wndcls))
            {
                AfxThrowResourceException();
                return FALSE;
            }
        }
    
        return TRUE;
    }
    

    In our example of creating the control dynamically, we should now change the creation call to

    m_Viewer.Create(_T("MFCBitmapViewerCtrl"), _T(""), WS_VISIBLE, CRect(0,0,100,100), this, 1);

    This will ensure the correct window styles, cursors and colors are used in the control. It's probably worthwhile writing a new Create function for your custom control so that users don't have to remember the window class name. For example:

    BOOL CBitmapViewer::Create(CWnd* pParentWnd, const RECT& rect, UINT nID, DWORD dwStyle /*=WS_VISIBLE*/)
    {
        return CWnd::Create(BITMAPVIEWER_CLASSNAME, _T(""), dwStyle, rect, pParentWnd, nID);
    }
    

    To use the custom control in a dialog resource, simply create a custom control on the dialog resource as you would any other control

    and then in the control's properties, specify the class name as "MFCBitmapViewerCtrl"

    The final step is to link up a member variable with the control. Simply declare an object of type CBitmapViewer in your dialog class (say, m_Viewer) and in your dialog's DoDataExchange add the following

    void CCustomControlDemoDlg::DoDataExchange(CDataExchange* pDX)
    {
        CDialog::DoDataExchange(pDX);
        //{{AFX_DATA_MAP(CCustomControlDemoDlg)
        DDX_Control(pDX, IDC_CUSTOM1, m_Viewer);
        //}}AFX_DATA_MAP
    }

    DDX_Control links the member variable m_Viewer with the control with ID IDC_CUSTOM1 by calling SubclassWindow. Creating a custom control in your dialog resource with the class name "MFCBitmapViewerCtrl" creates a window that behaves as your CBitmapViewer::RegisterWindowClass has specified, and then the DDX_Control call links your CBitmapViewer object with this pre-prepared window.

    Compile your project, run the application, and be amazed. You've just created a custom control.

    License

    This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    About the Author

    Chris Maunder
    Founder CodeProject
    Canada Canada
    Member
    Chris is the Co-founder, Administrator, Architect, Chief Editor and Shameless Hack who wrote and runs The Code Project. He's been programming since 1988 while pretending to be, in various guises, an astrophysicist, mathematician, physicist, hydrologist, geomorphologist, defence intelligence researcher and then, when all that got a bit rough on the nerves, a web developer. He is a Microsoft Visual C++ MVP both globally and for Canada locally.
     
    His programming experience includes C/C++, C#, SQL, MFC, ASP, ASP.NET, and far, far too much FORTRAN. He has worked on PocketPCs, AIX mainframes, Sun workstations, and a CRAY YMP C90 behemoth but finds notebooks take up less desk space.
     
    He dodges, he weaves, and he never gets enough sleep. He is kind to small animals.
     
    Chris was born and bred in Australia but splits his time between Toronto and Melbourne, depending on the weather. For relaxation he is into road cycling, snowboarding, rock climbing, and storm chasing.

    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

     
    You must Sign In to use this message board.
    Search this forum  
        Spacing  Noise  Layout  Per page   
    QuestionThank youmemberkill1421 Nov '12 - 15:26 
    Good Custom Controls!!!
    GeneralMy vote of 1memberhoseinhero2 Sep '12 - 7:05 
    poor coding
    QuestionThanks.memberMarty Barringer7 Jul '12 - 12:52 
    I've always struggled with how to apply the AfxRegisterClass() method. And create a custom control for that matter. This has simply shown the technique. Appreciate the posting. Now I can create a custom CStatic I'm in need of.
    QuestionHow to add bitmap from other loactionmembersayit2shoaib23 May '12 - 17:35 
    Hi...
     
    First of all I would like to thank you for sharing such a valuable information.
    I am a newbie to MFC so I don't know much, I would to ask you a question and that is
    how to apply an image that is located in some other location than the executable file
    to a custom control using LoadBitmap function of the CBitmap class as this function
    loads images from the executable file and not from other folder location as per
    MSDN.

    Please correct me if I am wrong at any point.
    I will appreciate your help.
     
    Thank You
    QuestionWhat if i have to handle more then one control?memberamarasat22 Jun '11 - 5:59 
    My question is what if i have two Checkboxes and a ListBox control in the CBitmapViewer class? I have to move a ListBox and two Checkboxes into a separate class and add that custom class to the dialog at the time of creation of the dialog. how can i do this?
    GeneralSolution for AfxGetInstanceHandle() language DLL failurememberScott Crawford10 Mar '11 - 11:20 
    After using AfxGetInstanceHandle() to load a language DLL for my application I
    found the resource dialogs which contained the custom controls began to fail
    from within CreateDialogIndirect.
     
    When a window class is registered that class name is good for that application's
    instance.   After loading the language DLL the dialogs now reside within a separate
    instance.  
     
    The solution I found was to add CS_GLOBALCLASS to the class registration.
    wndcls.style = CS_GLOBALCLASS | CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW;
     
    Further reading:
    Registering a Class in a DLL
    http://support.microsoft.com/kb/97758
    GeneralRe: Solution for AfxGetInstanceHandle() language DLL failurememberMithun Kadam22 Feb '12 - 23:04 
    Thank you so much for u r help.This post really give me huge amount of relief.
    Thanks once again.....................
    GeneralQuestionmemberthready4 Mar '10 - 16:45 
    Hi Chris,
     
    First of all, this article has made me a better programmer. I've used this method to create some very useful controls - a calendar being the most important one for a program I've been working on for years - so thanks for one of the most important articles for me!
     
    My question is this: I have created a win32 dll for resources and copied all the resources from my program to it. I optionally load this dll on startup (it basically changes the UI a bit by moving controls around). So there's absolutely no difference in any of the IDs of the controls. I noticed that the dialogs that contain custom controls don't load.
     
    I use the RegisterWindowClass function you have here. The following line loads the HINSTANCE:
    HINSTANCE hInst = AfxGetInstanceHandle();
     
    This is not the same HINSTANCE that is loaded by the resource dll, so the window doesn't exist when the window tries to DoModal....
     
    I hope you understand what I'm trying to say. Any idea what I can do?
     
    Many thanks,
    Mike
    GeneralRe: Questionmemberthready4 Mar '10 - 17:39 
    Actually, I passed a pointer of the instance on to my CWnd derived class before the init- but it still doesn't work. I have no idea why the dialogs with these types of controls won't display in my resource-only dll.
    QuestionHow to develop DLL for class which is used for custom controlmembergsheladia7 Jun '09 - 19:55 
    First of all like to say sorry that I am not native english speaker. As shown in above article how to make custom control ?, Now my query is how to make dll of that class which uses custom control ? I wants to make dll of the code which is using custom control and how to use that dll in another programm ?
     
    thanks ,
     
    Gunjan

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

    Permalink | Advertise | Privacy | Mobile
    Web04 | 2.6.130523.1 | Last Updated 12 May 2000
    Article Copyright 2000 by Chris Maunder
    Everything else Copyright © CodeProject, 1999-2013
    Terms of Use
    Layout: fixed | fluid